使用HttpURLConnection时,如果证书出问题,就可能抛出SSLHandshakeException的错误,这里可以通过设置HttpURLConnection信任所有证书的办法来临时解决这个问题。
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
{
Log.i("skyapp", "checkClientTrusted");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i("skyapp", "checkServerTrusted");
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
在openUrlConnection之前调用上述代码即可。