Https使用私有证书时,不验证证书:
- 自定义SSLContext,设置DefaultSSLSocketFactory
- 设置HostnameVerifier
URL resourceUrl = new URL("https://www.baidu.com/");
HttpURLConnection urlConnection = null;
if (resourceUrl.getProtocol().toUpperCase().equals("HTTPS")) {
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, mTrustManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
FYLog.writeError("https set SSLSocketFactory error: " + e.getMessage());
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) resourceUrl.openConnection();
httpsConnection.setHostnameVerifier(mHostVerifier);
urlConnection = httpsConnection;
} else {
urlConnection = (HttpURLConnection) resourceUrl.openConnection();
}
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
urlConnection.setUseCaches(false);
urlConnection.setInstanceFollowRedirects(followRedirects);
urlConnection.setDoInput(true);
...
private final HostnameVerifier mHostVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
FYLog.d("https HostnameVerifier verify, just return true");
return true;
}
};
private final TrustManager[] mTrustManager = new TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
网友评论