发新话题
打印

https请求报错unable to find valid certification path to requested target解决

https请求报错unable to find valid certification path to requested target解决

//忽略SSL验证
    public static void ignoreSSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {}
 
            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {}
 
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }};
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }
 
    public static void main(String[] args) throws Exception {
        ignoreSSL();
        // 创建URL对象
        URL url = new URL("https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg");
 
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 
        // 设置请求头参数
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
 
        // 发送请求
        int responseCode = connection.getResponseCode();
 
        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
 
        // 输出响应
        System.out.println("Response Code: " + responseCode);
        System.out.println("Response Body: " + response.toString());
 
        // 关闭连接
        connection.disconnect();
    }


亲测,好用~~

TOP

发新话题