java 任何 Apache HttpClient 4.4 信任自签名证书示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30250102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Any Apache HttpClient 4.4 Example for trust self signed certificates
提问by Alin Huang
I changed HttpClient
version from old version to the new 4.4
.
我将HttpClient
版本从旧版本更改为新版本4.4
。
And got many deprecated method and Class. The original codes can trust self signed certificates and I want to replace to new method and Class.
并获得了许多不推荐使用的方法和类。原始代码可以信任自签名证书,我想替换为新方法和类。
Could any one give me a guide line how to replace or any example code?
任何人都可以给我一个指导方针如何替换或任何示例代码?
Thank you.
谢谢你。
回答by Alin Huang
Thanks for reply, I found a sample code as below
感谢回复,我找到了一个示例代码如下
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);
回答by zakmck
I could successfully disable the certificate verification (remember, it's insecure), by using the Alin's answer, but I had to modify his code this way:
我可以通过使用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();
...
As you can see, I use the most liberal TrustStrategy
possible, because TrustSelfSignedStrategy
was giving me "unable to find valid certification path to requested target". Moreover, it seems I don't need to pass new String[] { "TLSv1" }
to SSLConnectionSocketFactory
, null
should be interpreted as "all protocols".
如您所见,我使用了最宽松TrustStrategy
的方法,因为TrustSelfSignedStrategy
这让我“无法找到到请求目标的有效认证路径”。而且,似乎我不需要传递new String[] { "TLSv1" }
给SSLConnectionSocketFactory
,null
应该解释为“所有协议”。
This is now available here, which you can link from Maven, through the repo reported here.
回答by gredezcici
i work with httpclient 4.5.2, you can use following code to bypass certificate verification, hope this helps
我使用 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);
回答by EpicPandaForce
As far as I know (I used 4.3), the following ought to work:
据我所知(我使用 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();
}
....