1 packagecom.lenovo.biportal.utils.bitool; 2 3 importjavax.net.ssl.HostnameVerifier; 4 importjavax.net.ssl.HttpsURLConnection; 5 importjavax.net.ssl.SSLContext; 6 importjavax.net.ssl.X509TrustManager; 7 importjava.io.BufferedReader; 8 importjava.io.InputStream; 9 importjava.io.InputStreamReader; 10 importjava.net.HttpURLConnection; 11 12 public classSSL { 13 final static HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true; 14 15 public static voidhttpGet(String path) { 16 StringBuffer tempStr = newStringBuffer(); 17 String responseContent = ""; 18 HttpURLConnection conn = null; 19 try{ 20 //Create a trust manager that does not validate certificate chains 21 trustAllHosts(); 22 URL url = newURL(path); 23 HttpsURLConnection https =(HttpsURLConnection) url.openConnection(); 24 if (url.getProtocol().toLowerCase().equals("https")) { 25 https.setHostnameVerifier(DO_NOT_VERIFY); 26 conn =https; 27 } else{ 28 conn =(HttpURLConnection) url.openConnection(); 29 } 30 conn.connect(); 31 System.out.println("地址:" + path + ", success, result: " + conn.getResponseCode() + " " +conn.getResponseMessage()); 32 //HttpURLConnection conn = (HttpURLConnection) 33 //url.openConnection(); 34 35 //conn.setConnectTimeout(5000); 36 //conn.setReadTimeout(5000); 37 //conn.setDoOutput(true); 38 39 InputStream in =conn.getInputStream(); 40 conn.setReadTimeout(10 * 1000); 41 BufferedReader rd = new BufferedReader(newInputStreamReader(in, 42 "UTF-8")); 43 String tempLine; 44 while ((tempLine = rd.readLine()) != null) { 45 tempStr.append(tempLine); 46 } 47 responseContent =tempStr.toString(); 48 System.out.println(responseContent); 49 rd.close(); 50 in.close(); 51 } catch(Exception e) { 52 logger.error("地址:{}, ins error", e); 53 } finally{ 54 if (conn != null) { 55 conn.disconnect(); 56 } 57 } 58 } 59 60 /** 61 * Trust every server - dont check for any certificate 62 */ 63 public static voidtrustAllHosts() { 64 65 //Create a trust manager that does not validate certificate chains 66 TrustManager[] trustAllCerts = new TrustManager[]{newX509TrustManager() { 67 68 publicjava.security.cert.X509Certificate[] getAcceptedIssuers() { 69 return newjava.security.cert.X509Certificate[]{}; 70 } 71 72 public voidcheckClientTrusted(X509Certificate[] chain, String authType) { 73 74 } 75 76 public voidcheckServerTrusted(X509Certificate[] chain, String authType) { 77 78 } 79 }}; 80 81 //Install the all-trusting trust manager 82 //忽略HTTPS请求的SSL证书,必须在openConnection之前调用 83 try{ 84 SSLContext sc = SSLContext.getInstance("TLS"); 85 sc.init(null, trustAllCerts, newjava.security.SecureRandom()); 86 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 87 } catch(Exception e) { 88 System.out.println("trustAllHosts is error" +e); 89 } 90 } 91 92 }
转载:
https://ningyu1.github.io/site/post/53-ssl-cert-3/