背景:开发时需要根据rest api访问第三方接口数据,本地访问http://localhost可以正确访问,当访问服务器,项目路径变成了https://xx.xx.xx,出现javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present问题。
先在访问url的java类里增加以下代码:
//配置认证管理器
HttpsURLConnection.setDefaultHostnameVerifier(new Restful().new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
增加绕过证书认证的代码:
static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
} };
//激活主机认证
public class NullHostNameVerifier implements HostnameVerifier {
/*
* (non-Javadoc)
*
* @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
* javax.net.ssl.SSLSession)
*/
@Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
}