Android https 私有证书,不验证证书

2018-01-02  本文已影响0人  goodl

Https使用私有证书时,不验证证书:


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 {
    }
}};
上一篇 下一篇

猜你喜欢

热点阅读