异常提示:
javax.nex.ssl.SSLHandshakeException:No appropriate protocol(protocol is disabled or cipher suites are inappropriate)
原因:远程服务认证失败
解决方案:
方案一:修改jdk配置
jdk -> conf -> security ->java.security文件
将 jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, ...
替换为 jdk.tls.disabledAlgorithms=SSLv3, RC4...
(删除SSLv3,TLSv1)
方案二:代码实现(添加证书信任认证)
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class TrustAllManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
// 不对客户端进行验证
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
// 信任所有服务器证书,不抛出异常
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.HttpsURLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
public class SSLTrustExample {
public static void main(String[] args) {
// 创建自定义 TrustManager
TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllManager() };
try {
// 获取默认的 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
// 初始化 SSLContext,使用自定义 TrustManager
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// 在 HttpsURLConnection 中设置 SSLContext
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
// 可选:禁用主机名验证(可信任所有服务器主机名)
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
// 发送 HTTPS 请求
// ...
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
}
}