信任自签名证书的任何 Apache HttpClient 4.4 示例

Any Apache HttpClient 4.4 Example for trust self signed certificates

我将 HttpClient 版本从旧版本更改为新版本 4.4

并且得到了许多弃用的方法和 Class。原始代码可以信任自签名证书,我想替换为新方法和 Class。

任何人都可以给我一个如何替换的指南或任何示例代码吗?

谢谢。

据我所知(我使用的是 4.3),以下应该有效:

   ....
        SSLContext sslContext = SSLContexts.custom()         
        .loadTrustMaterial((KeyStore)null, new TrustSelfSignedStrategy()) 
               //I had a trust store of my own, and this might not work!
        .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        CloseableHttpClient httpclient = HttpClients
            .custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
            .setSSLSocketFactory(sslsf).build();
        CloseableHttpResponse response = httpclient.execute(httpUriRequest);
        try {
            HttpEntity entity = response.getEntity();
            //do things
            if(entity != null) {
                entity.consumeContent();
            }
        } finally {
            response.close();
        }
   ....

感谢回复,我找到了一个示例代码如下

SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
        new TrustSelfSignedStrategy()).build();

// Allow TLSv1 protocol only, use NoopHostnameVerifier to trust self-singed cert
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
        new String[] { "TLSv1" }, null, new NoopHostnameVerifier());

//do not set connection manager
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

HttpPost httpPost = new HttpPost(url);

RequestConfig defaultRequestConfig = RequestConfig
        .custom()
        .setCookieSpec(CookieSpecs.DEFAULT)
        .setExpectContinueEnabled(true)
        .setTargetPreferredAuthSchemes(
                Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
        .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
        .setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT)
        .setConnectionRequestTimeout(TIME_OUT).build();
httpPost.setConfig(requestConfig);

httpPost.setHeader("Content-type", "application/json");
StringEntity mEntity = new StringEntity(arg, "UTF-8");
mEntity.setContentType("application/json;charset=UTF-8");
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
        "application/json;charset=UTF-8"));
httpPost.setEntity(mEntity);

response = httpclient.execute(httpPost);

我使用的是httpclient 4.5.2,你可以使用下面的代码绕过证书验证,希望对你有帮助

CloseableHttpClient client = HttpClients.custom()
      .setSSLContext(sslContext)
      .setSSLHostnameVerifier(new NoopHostnameVerifier())
      .build();

HttpPost post = new HttpPost(url);
//set post headers and params 
post.setHeader(....);
HttpResponse response = client.execute(post);

我可以使用 成功禁用证书验证(记住,它是不安全的),但我不得不这样修改他的代码:

SSLContext sslcontext = 
SSLContexts
.custom ()
.loadTrustMaterial ( 
    null, 
    new TrustStrategy ()
    {
        public boolean isTrusted ( X509Certificate[] chain, String authType ) throws CertificateException {
            return true;
        }
    })
.build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory ( 
    sslcontext, null, null, new NoopHostnameVerifier () 
);

HttpClient httpClient = HttpClients
    .custom()
    .setSSLSocketFactory ( sslsf )
    .build();

... 

如您所见,我使用了最宽松的 TrustStrategy 可能,因为 TrustSelfSignedStrategy 给我“无法找到请求目标的有效证书路径”。而且,似乎我不需要将new String[] { "TLSv1" }传递给SSLConnectionSocketFactorynull应该被解释为“所有协议”。

现在可用 here, which you can link from Maven, through the repo reported here