原链接:http://www.programcreek.com/java-api-examples/index.php?api=org.apache.http.conn.socket.ConnectionSocketFactory

点击(此处)折叠或打开

  1. private HttpResponse handleCertificateExceptionAndRetry(IOException e,
  2.                                                         HttpRequestBase method,
  3.                                                         HttpClientBuilder client,
  4.                                                         @Nullable HttpContext context)
  5.         throws IOException {
  6.     if (!isCertificateException(e)) {
  7.         throw e;
  8.     }

  9.     if (isTrusted(method.getURI().getAuthority())) {
  10.         // creating a special configuration that allows connections to non-trusted HTTPS hosts
  11.         try {
  12.             SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
  13.             sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
  14.                 @Override
  15.                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  16.                     return true;
  17.                 }
  18.             });
  19.             SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
  20.                     sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

  21.             Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  22.                     .register("https", sslConnectionSocketFactory)
  23.                     .build();

  24.             PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  25.             client.setConnectionManager(connectionManager);
  26.         } catch (Exception sslException) {
  27.             throw Throwables.propagate(sslException);
  28.         }
  29.         return client.build().execute(method, context);
  30.     }
  31.     throw e;
  32. }

09-28 00:19