HttpClient通过加载证书进行网络请求

2017-06-30  本文已影响0人  linweiyu21

需求

请求某个接口时,需要走HTTPS协议,使用指定的证书.在本例中的证书为PFX的自定义证书.

代码

注:HttpClient的版本为4.2

    /**
     * @param keyStorePath 密钥库路径
     * @param keyStorepass 密钥库密码
     * @return
     */
    public static HttpClient customSSLClient(String keyStorePath, String keyStorepass) throws Exception {
        HttpClient httpClient;
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File(keyStorePath));
        try {
            trustStore.load(instream, keyStorepass.toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }
        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore, keyStorepass.toCharArray());
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
        return httpClient;
    }

SSLSocketFactoryEx

private static class SSLSocketFactoryEx extends SSLSocketFactory {

        SSLContext sslContext = SSLContext.getInstance("TLS");

        public SSLSocketFactoryEx(KeyStore truststore, char[] arry)
                throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException {
            super(truststore);
            KeyManagerFactory localKeyManagerFactory =
                    KeyManagerFactory.getInstance(KeyManagerFactory
                            .getDefaultAlgorithm());
            localKeyManagerFactory.init(truststore, arry);
            KeyManager[] arrayOfKeyManager =
                    localKeyManagerFactory.getKeyManagers();
            TrustManager tm = new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {

                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {

                }
            };

            sslContext.init(arrayOfKeyManager, new TrustManager[]{tm},
                    new java.security.SecureRandom());
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port,
                                   boolean autoClose) throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host, port,
                    autoClose);
        }

        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
        }
    }

参考

HttpClient4.2官方例子
本例主要参考的文章

上一篇下一篇

猜你喜欢

热点阅读