你的位置:首页 > Java教程

[Java教程]HttpsURLConnection

package test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.KeyManager;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;public class Test {  public static void main(String[] args) {    HttpsURLConnection conn = null;    try {      URL url = new URL("https://home.cnblogs.com/u/mjn0");      conn = (HttpsURLConnection) url.openConnection();      SSLContext context = SSLContext.getInstance("TLS");      X509TrustManager xtm = new X509TrustManager() {        @Override        public X509Certificate[] getAcceptedIssuers() {          return null;        }        @Override        public void checkServerTrusted(X509Certificate[] chain, String authType)            throws CertificateException {        }        @Override        public void checkClientTrusted(X509Certificate[] chain, String authType)            throws CertificateException {        }      };      KeyManager[] km = null;      TrustManager[] tm = new TrustManager[] { xtm };      SecureRandom random = null;      context.init(km, tm, random);      SSLSocketFactory sf = context.getSocketFactory();      conn.setSSLSocketFactory(sf);    } catch (MalformedURLException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    } catch (NoSuchAlgorithmException e) {      e.printStackTrace();    } catch (KeyManagementException e) {      e.printStackTrace();    }    try (InputStream is = conn.getInputStream();        InputStreamReader isr = new InputStreamReader(is, "utf-8");        BufferedReader br = new BufferedReader(isr);) {      String line;      while ((line = br.readLine()) != null) {        System.out.println(line);      }    } catch (IOException e) {      e.printStackTrace();    }  }}