综合csdn,stackoverflow上文章进行总结整理
Bug背景:
通过apache httpclient做系统间文件传递时使用到了https方式进行访问,client获取方式为:CloseableHttpClient client = HttpClients.createDefault();
请求报错:Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
自定义CloseableHttpClient 生成方式,创建类 SeeSSLCloseableHttpClient
public class SeeSSLCloseableHttpClient {
private static X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
public static CloseableHttpClient getCloseableHttpClient() {
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { tm }, null);
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(ctx,
NoopHostnameVerifier.INSTANCE);
builder.setSSLSocketFactory(sslConnectionFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslConnectionFactory).build();
HttpClientConnectionManager ccm1 = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm1);
return builder.build();
}
}
获取
CloseableHttpClient 方式由原来
CloseableHttpClient client = HttpClients.createDefault();更改为
CloseableHttpClient client = SeeSSLCloseableHttpClient.getCloseableHttpClient();
运行正确。