You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OkHttp中实现信任所有证书?求代码整合指导

Got it, let's walk through how to integrate the trust-all-certificates logic into your existing OkHttp code step by step. I'll adapt the trusted "Trusting all certificates with okHttp" approach to fit your current implementation perfectly.

Modified Full Code

Here's your updated class with the certificate trust logic integrated:

import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;

public class Handler_JSON_get_accept_auth {
    public Handler_JSON_get_accept_auth() {
    }

    public String makeServiceCall(String url, String auth) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // Use our custom OkHttpClient with trust-all-certificate settings (debug only!)
        OkHttpClient client = getUnsafeOkHttpClient();
        
        Request request = new Request.Builder()
                .url(url)
                .header("Accept","application/json")
                .header("Authorization",auth)
                .get()
                .build();
        
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            // Handle timeout or other exceptions
            return null;
        }
    }

    // Helper method to create an OkHttpClient that trusts all certificates
    private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a TrustManager that doesn't validate certificate chains
            final X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {}

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {}

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            };

            // Initialize SSLContext with our trust-all TrustManager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // Build the OkHttpClient with your original settings + SSL overrides
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, trustManager);
            builder.hostnameVerifier((hostname, session) -> true); // Bypass hostname validation
            builder.connectTimeout(45, TimeUnit.SECONDS);
            builder.readTimeout(45, TimeUnit.SECONDS);
            builder.protocols(Arrays.asList(Protocol.HTTP_1_1));

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Key Changes Explained

  • Custom TrustManager: We added a X509TrustManager that skips all certificate validation checks—this tells OkHttp to accept any server certificate, even self-signed or expired ones.
  • SSL Context Setup: We initialized an SSLContext with our trust-all manager, then extracted the SSLSocketFactory to attach to OkHttp.
  • Hostname Verifier: The lambda (hostname, session) -> true skips checking if the server's hostname matches the certificate's common name, another critical SSL check we bypass for debugging.
  • Reused Your Original Config: All your existing timeout and protocol settings are preserved in the OkHttpClient.Builder—we just added the SSL-related overrides on top.

Critical Warning

⚠️ Do NOT use this code in production! Disabling SSL validation completely removes protection against man-in-the-middle attacks. This is only safe for local debugging or testing against internal servers you fully trust.

内容的提问来源于stack exchange,提问作者Sergio76

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:25:35