最近发现在做https请求时,会报出SSL握手异常
- javax.net.ssl.SSLHandshakeException: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate signature.
仔细看了下,用HttpUrlConnection做https请求,应该是没有信任所有证书,导致请求失败的。
上网学习了一下,发现需要实现X509TrustManager接口创建一个证书,然后使用我们自己创建的信任管理器初始化SSLContext 对象。
-
-
-
- private static void trustAllHosts() {
-
- TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return new java.security.cert.X509Certificate[] {};
- }
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- Log.i("skyapp", "checkClientTrusted");
- }
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- Log.i("skyapp", "checkServerTrusted");
- }
- } };
-
- try {
- SSLContext sc = SSLContext.getInstance("TLS");
- sc.init(null, trustAllCerts, new java.security.SecureRandom());
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
在我们HttpURLConnection调用openConnection之前,执行一下trustAllHosts方法,信任所有证书,即可正常进行https请求。
以上是HttpURLConnection类证书信任问题导致的https请求异常解决方案,而如果用到HttpClient的话,则需要另外的解决方法。
在HttpClient执行excute之前,执行以下语句即可
- SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());