http连接和https连接不同.所以要分开处理,http就不说了。
1、先查看服务器https的版本号
2、自定义能为https服务的HttpClient
//构造能进行https通讯,httpClient对象
public static CloseableHttpClient createSSLClient(){
SSLContext sslContext=null;
try{
//这个TLSV1.2必须是和服务器匹配的版本号(一定要匹配)
sslContext=SSLContext.getInstance("TLSV1.2");
HttpsTrustManager hm=new HttpsTrustManager();//自定义的信任管理器
sslContext.init(null,new X509TrustManager[]{hm}, new SecureRandom());
SSLConnectionSocketFactory factory=new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(factory).build();
}catch(Exception e){
return null;
}
}
/*HttpPost如何使用SSL ?
* https://blog.csdn.net/defonds/article/details/86594441
* 除了信任所有客户端之外什么也不做。它只是简单的实现了 X509TrustManager 并自动生成了所有的方法。
* */
class HttpsTrustManager implements X509TrustManager{
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return new X509Certificate[]{};
}
}
//根据网址实例化HttpClient,http和https是分开的
CloseableHttpClient httpClient =url.startsWith("https")?createSSLClient(): HttpClients.createDefault();
这里要感谢另外2个帖子提供的帮助
https://blog.csdn.net/m0_37825799/article/details/95367343