在Java项目中请求HTTPS时,可能会遇到 "unable to find valid certification path to requested target" 错误。这个错误通常是由于SSL证书问题引起的。要解决此问题,可以尝试以下方法
1.忽略SSL验证
OkHttpClient封装请求
public static OkHttpClient getUnsafeOkHttpClient() { try { // 创建一个信任所有证书的TrustManager final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; // 创建一个不验证证书的 SSLContext,并使用上面的TrustManager初始化 SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // 使用上面创建的SSLContext创建一个SSLSocketFactory javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); builder.hostnameVerifier((hostname, session) -> true); builder.readTimeout(1, TimeUnit.MINUTES); return builder.build(); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { // 发送请求 Request request = new Request.Builder() .url("https://example.com") .build(); Response response = getUnsafeOkHttpClient().newCall(request).execute(); System.out.println(response.body().string()); }
CloseableHttpClient请求
public static void main(String[] args) throws Exception { // 创建SSL上下文,忽略证书验证 SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); // 创建 CloseableHttpClient 对象 CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build(); // 创建 HttpGet 对象,并设置请求URL HttpGet httpGet = new HttpGet("https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg"); // 设置请求头参数 httpGet.setHeader("User-Agent", "Mozilla/5.0"); // 发送请求,获取响应 HttpResponse response = httpClient.execute(httpGet); // 获取响应实体 HttpEntity entity = response.getEntity(); // 读取响应内容 String responseBody = EntityUtils.toString(entity); // 输出响应 System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); System.out.println("Response Body: " + responseBody); // 关闭httpClient httpClient.close(); }
HttpURLConnection请求
//忽略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(); }
RestTemplate请求
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 str[]) throws Exception{ ignoreSSL(); RestTemplate restTemplate = new RestTemplate(); ResponseEntityresponse = restTemplate.getForEntity("https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg", String.class); System.out.println(response.getBody()); }
2.添加证书到本地证书库
-
获取证书,首先确保您访问的HTTPS网站具有有效的SSL证书。可以通过浏览器访问该网站并查看并导出证书。
-
导入SSL证书:将SSL证书导入到Java的信任存储库中。可以使用keytool命令行工具执行此操作。运行以下命令将证书导入到默认的JDK信任存储库中
-
keytool -import -alias alias_name -keystore path_to_jdk_cacerts -file path_to_certificate -- alias_name 证书指定的别名 -- path_to_jdk_cacerts是JDK信任存储库的路径,默认路径为$JAVA_HOME/jre/lib/security/cacerts, -- path_to_certificate是下载的SSL证书的路径
-
-
还没有评论,来说两句吧...