gpt4 book ai didi

java - 将自定义证书添加到 OkHttp 客户端

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:46 30 4
gpt4 key购买 nike

我正在尝试制作 Android 应用程序,我可以在其中获取和解析 HTML(来自没有 API 的网站)。我正在使用 OkHttp。该站点具有不受信任(但有效)的证书。我得到:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

我已经设置了官方方式(https://developer.android.com/training/articles/security-ssl#java),现在我需要将它与 OkHttpClient 链接。

我试过了

    OkHttpClient client = new OkHttpClient;

OkHttpClient.Builder builder = client.newBuilder();
builder.sslSocketFactory(sslcontext.getSocketFactory()).build();

但是它不起作用,而且它也被弃用了。谢谢

最佳答案

请参阅此文档示例以添加已知的受信任证书

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java

  public CustomTrust() {
X509TrustManager trustManager;
SSLSocketFactory sslSocketFactory;
try {
trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}

client = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.build();
}

关于java - 将自定义证书添加到 OkHttp 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304082/

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