Apache HttpClient请求 unable to find valid certification path to requested target解决方案

综合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();

运行正确。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值