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

时间:2015-05-15 01:27:58

标签: java ssl httpclient

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

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

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

谢谢。

4 个答案:

答案 0 :(得分:4)

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

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);

答案 1 :(得分:3)

我可以使用Alin's answer成功禁用证书验证(请记住,这是不安全的),但我必须以这种方式修改其代码:

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,您可以从Maven链接到报告的回复here

答案 2 :(得分:2)

我使用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);

答案 3 :(得分:1)

据我所知(我使用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();
        }
   ....