我正在尝试使用 java 获取站点的内容。像这样
package javaTests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class PrintContent {
public static void main(String[] args) throws Exception {
String https_url = "https://api.precharge.net/charge";
URL url;
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
if(con!=null){
try {
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
但是我遇到了异常。
javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径
请就如何解决此问题提出一些建议。提前谢谢你。
我也尝试将证书复制到 java 的安全文件夹中。但它不工作。还尝试了 installcerticate.java 类。
如果您未能在信任库中安装证书,您可以使用此技巧来禁用 SSL 验证。不应在生产环境中使用。
package javaTests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
import java.security.SecureRandom;
public class PrintContent {
public static void main(String[] args) throws Exception {
String https_url = "https://api.precharge.net/charge";
URL url;
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
if (con != null) {
try {
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null) {
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void disableCertificates() {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
System.out.println("Warning! SSL validation has been disabled!");
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
System.out.println("Warning! SSL validation has been disabled!");
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
System.out.println("Warning! SSL validation has been disabled!");
}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
System.out.println("Failed to disable SSL validation," + e.getMessage());
}
}
}
我是一名优秀的程序员,十分优秀!