針對一般的http請求是不需要的校驗的。但是https安全校驗過總過不去。最后找到以下方法,終於成功。
讓我們的站點信任所有站點,不需要引包,系統自帶ssl證書校驗,話不多數,貼代碼。
/** * 信任任何站點,實現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(); } }
以下是引用的類,大家被搞錯了。
import java.io.UnsupportedEncodingException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager;
然后就是使用了 ,
在需要進行創建請求對象之前加入這個方法就行。
實例:
trustEveryone(); Connection conn = HttpConnection2.connect(url); conn.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); conn.header("Accept-Encoding", "gzip, deflate, br"); conn.header("Accept-Language", "zh-CN,zh;q=0.9"); conn.header("Cache-Control", "max-age=0"); conn.header("Connection", "keep-alive"); conn.header("Host", "blog.maxleap.cn"); conn.header("Upgrade-Insecure-Requests", "1"); conn.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"); Document doc = null;
好了,然后就可以正常訪問了。
親測有效,這是目前我正在使用的方法。
---------------------
作者:月光下的豬
來源:CSDN
原文:https://blog.csdn.net/shaochong047/article/details/79636142
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!