java okhttp3 绕过ssl验证
时间: 2023-10-04 16:07:13 浏览: 151
在 OkHttp3 中,可以通过配置 OkHttpClient 实例的 SSLSocketFactory 和 TrustManager 来实现绕过 SSL 验证,具体如下:
```java
// 创建一个信任所有证书的 TrustManager
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 SecureRandom());
// 创建一个 OkHttpClient 实例,并设置 SSLContext
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
.hostnameVerifier((hostname, session) -> true)
.build();
// 发送请求
Request request = new Request.Builder()
.url("https://example.com")
.build();
Response response = client.newCall(request).execute();
```
在上面的代码中,我们创建了一个 TrustManager 实例,用于信任所有证书。然后使用这个 TrustManager 初始化一个 SSLContext,最后将这个 SSLContext 设置到 OkHttpClient 实例中。
需要注意的是,绕过 SSL 验证可能会带来安全风险,应该尽量避免在生产环境中使用。
阅读全文
相关推荐

















