美文网首页
Android https 私有证书,不验证证书

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

作者: goodl | 来源:发表于2018-01-02 17:43 被阅读0次

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 {
    }
}};

相关文章

网友评论

      本文标题:Android https 私有证书,不验证证书

      本文链接:https://www.haomeiwen.com/subject/kadqnxtx.html