前幾天用JSOUP寫爬蟲Demo時,遇到這個異常
百度了一番原來是因為目標站點啟用了HTTPS 而缺少安全證書時出現的異常,大概解決辦法有2種:
1. 手動導入安全證書(嫌麻煩 沒使用);
2. 忽略證書驗證。
相對於來說簡單一點,在發起請求前調用這個方法,問題解決。
// 包不要導錯了
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 信任任何站點,實現https頁面的正常訪問
*/
public static void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}