信任自签名证书的任何Apache HttpClient 4.4示例
问题描述:
我将HttpClient
版本从旧版本更改为新的4.4
.
I changed HttpClient
version from old version to the new 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?
谢谢.
答
感谢您的答复,我发现了以下示例代码
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);