Java HttpsURLConnection忽略crt访问https链接

访问https时,需要验证ssl证书,使用HttpsURLConnection访问一个我们已经信任的https页面,需要跳过crt验证时,可以参考如下代码

public static void main(String argv[]){
        String urlStr = "https://github.com/Unknwon/go-fundamental-programming";
        try {
            URL url = new URL(urlStr);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

            TrustManager[] trustManagers = new TrustManager[]{
                    new X509TrustManager() {
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }

                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }

                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                    }
            };
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null,trustManagers,null);

            connection.setSSLSocketFactory(ctx.getSocketFactory());
            connection.setRequestMethod("GET");

            System.out.println(connection.getResponseCode());

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine())!=null){
                sb.append(line);
                sb.append("\n");
            }
            String response = sb.toString();
            System.out.print(response);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

版权声明:本文为freesonWANG原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。