Ali*_*ang 3 java ssl httpclient
我将HttpClient版本从旧版本更改为新版本4.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);
Run Code Online (Sandbox Code Playgroud)
我可以通过使用Alin 的答案成功禁用证书验证(记住,它是不安全的),但我必须这样修改他的代码:
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();
...
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我使用了尽可能自由的TrustStrategy方式,因为TrustSelfSignedStrategy这让我“无法找到到达所请求目标的有效认证路径”。而且,看来我不需要传递new String[] { "TLSv1" }to SSLConnectionSocketFactory,null应该解释为“所有协议”。
现在可以在此处获得,您可以通过此处报告的存储库从 Maven 链接到该内容。
| 归档时间: |
|
| 查看次数: |
14647 次 |
| 最近记录: |