调用问题错误日志
Received fatal alert: handshake_failure
该问题主要是jdk1.7默认使用的握手协议为TLSv1,而服务端jdk1.8默认使用的TLSv1.2,故在调用时会导致验证失败,通过查看源码了解代码中存在几个大坑
-
如果HttpClient调用过程中使用了PoolingHttpClientConnectionManager连接池,该连接池会自动忽略在连接时设定的 SSLContext ctx = SSLContext.getInstance(“TLS”);,需要在创建连接池管理的时候设置进去才行
SSLContext ctx = SSLContext.getInstance(“TLS”); // 创建一个上下文(此处指定的协议类型似乎不是重点)
X509TrustManager tm = new X509TrustManager() { // 创建一个跳过SSL证书的策略
public X509Certificate[] getAcceptedIssuers() {
return null;
}public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } }; ctx.init(null, new TrustManager[]{tm}, null); // 使用上面的策略初始化上下文 SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, new String[]{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", ssf) .build();
-
如果HttpClient调用过程中未使用PoolingHttpClientConnectionManager连接池,择需要在连接是设定默认的握手协议:
X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
CloseableHttpResponse response = null;
HttpEntity resEntity = null;
try{
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sc);
CloseableHttpClient httpClient = getClient(sslsf);
HttpPost httpPost = new HttpPost(url);
}。。。。