jdk1.6版本解决https链接访问问题

本文介绍了在使用JDK1.6时遇到HTTPS连接hostname in certificate didn't match问题的原因,由于SNI支持需要更高版本的JDK。解决方案包括升级JDK或自定义忽略hostname校验的HTTPS客户端。提供了自定义HTTPS客户端的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:访问https出现hostname in certificate didn't match问题,本地测试正常原因是本地环境支持了SNI(Server Name Indication),虚拟主机大力发展起来,造成了一个IP会对应多个域名的情况,SNI就是专门用于解决这个问题,它允许客户端在发起SSL握手请求时,就提交请求的Host信息,使得服务器能够切换到正确的域并返回相应的证书。
在java客户端上,SNI要求JDK至少到1.7,HttpClient至少到4.3.2,本地测试环境满足该要求,而线上环境JDK是1.6的所以会有问题。

解决办法

1,升级运行环境到满足SNI的要求

2,选择忽略hostname校验

可以创建X509HostnameVerifier,重载verify(String hostname, SSLSession session)方法返回true,并设置到httpclient,用于https请求。

新建MyHttpsClient 类

public class MyHttpsClient {


public static MyHttpsClient getInstance(){
return new MyHttpsClient();
}
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException{
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext, new X509HostnameVerifier() {


@Override
public void verify(String arg0, SSLSocket arg1)
throws IOException {
// TODO Auto-generated method stub

}


@Override
public void verify(String arg0, X509Certificate arg1)
throws SSLException {
// TODO Auto-generated method stub
}


@Override
public void verify(String arg0, String[] arg1, String[] arg2)
throws SSLException {
// TODO Auto-generated method stub

}


@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
        });


Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
        .<ConnectionSocketFactory> create().register("https", sslsf)
        .build();


PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
        socketFactoryRegistry);
CloseableHttpClient httpclient = HttpClients.custom()
        .setConnectionManager(cm).build();
return httpclient;
}
}


在HttpUtil中,使用 CloseableHttpClient httpclient = MyHttpsClient.getInstance().createHttpClient();

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值