gpt4 book ai didi

java - HttpClient https Post 请求失败

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:30 26 4
gpt4 key购买 nike

我正在尝试以下一种方式发出post请求:

  • 我使用 Apache 的 HttpClient 3.1
  • 我使用编码“application/x-www-form-urlencoded”
  • 我使用的 URL 以 https 开头

这是我尝试运行的代码:

public static String httpsPost(String url, String body, String mediaType, String encoding) {
disableCertificateValidation();
HttpClient client = new HttpClient();
StringRequestEntity requestEntity = new StringRequestEntity(body, mediaType, encoding);
PostMethod method = new PostMethod(url);
method.setRequestEntity(requestEntity);
client.executeMethod(method);
}

public static void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};

// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};

// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {}
}

在执行 executeMethod 时,我发现:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

我试过 disable certificate validation但这没有帮助。

最佳答案

如果您想完全忽略证书,请查看此处的答案 Ignore self-signed ssl cert using Jersey Client

尽管这会使您的应用容易受到中间人攻击。

您可以尝试将证书作为受信任的证书添加到您的 Java 存储中,而不是这样做。这个网站可能会有帮助。 http://blog.icodejava.com/tag/get-public-key-of-ssl-certificate-in-java/

这是显示如何向您的商店添加证书的另一个答案。 Java SSL connect, add server cert to keystore programatically

关键是

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(someCert);
ks.setEntry("someAlias", newEntry, null);`

关于java - HttpClient https Post 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31786727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com