由于时间原因,这里只构建所有请求https都能通过的请求client
首先定义(重写)信任管理器
public class SSLTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager ,HostnameVerifier{ public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } @Override public boolean verify(String urlHostName, SSLSession session) { //允许所有主机 return true; } }
然后封装
public static HttpURLConnection connect(String strUrl) throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLTrustManager(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext .getInstance("SSL"); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc .getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((HostnameVerifier) tm); URL url = new URL(strUrl); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); return urlConn; }
测试一下
public void unitest(){ HttpURLConnection urlConn = connect('https://github.com/'); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.connect(); InputStream is = urlConn.getInputStream(); StringBuffer sb = new StringBuffer(); if(is!=null) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s = null; while ((s=br.readLine())!=null) { sb.append(s).append("\n"); } } System.out.println("Content:\n"+sb.toString());}
try do it!