okhttp忽略SSL证书验证

2020-08-06 284

场景描述:Java程序调用其他自签证书https接口

  • 错误信息
javax.net.ssl.SSLPeerUnverifiedException: Hostname ip not verified:
  • 解决办法
public OkHttpClient getUnsafeOkHttpClient() { try { final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return builder.build(); } catch (Exception e) { throw new RuntimeException(e); } }
  • 使用方法
//将原来的 OkHttpClient okHttpClient = new OkHttpClient(); //替换为 OkHttpClient okHttpClient = new Test().getUnsafeOkHttpClient(); //Test为类名,若为静态方法直接类名.方法名调用即可
注:代码来自网络CSDN-蚕蛹的今生,稍微修改。
5 3