记录这个的原因,是因为很多时候,因为后台配置的证书不正确导致APP访问不到服务器数据,导致影响自身的开发进度。没几行代码,逻辑也清晰,所以下面就直接贴出工具类吧:
1 package huolongluo.yeshen.byw.injection.model; 2 3 import java.security.SecureRandom; 4 import java.security.cert.X509Certificate; 5 6 import javax.net.ssl.HostnameVerifier; 7 import javax.net.ssl.SSLContext; 8 import javax.net.ssl.SSLSession; 9 import javax.net.ssl.SSLSocketFactory; 10 import javax.net.ssl.TrustManager; 11 import javax.net.ssl.X509TrustManager; 12 13 /** 14 * Created by 火龙裸先生 on 2018/1/26. 15 * <p> 16 * 忽略https证书验证 17 */ 18 19 public class SSLSocketClient 20 { 21 //获取这个SSLSocketFactory 22 public static SSLSocketFactory getSSLSocketFactory() 23 { 24 try 25 { 26 SSLContext sslContext = SSLContext.getInstance("SSL"); 27 sslContext.init(null, getTrustManager(), new SecureRandom()); 28 return sslContext.getSocketFactory(); 29 } 30 catch (Exception e) 31 { 32 throw new RuntimeException(e); 33 } 34 } 35 36 //获取TrustManager 37 private static TrustManager[] getTrustManager() 38 { 39 TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() 40 { 41 @Override 42 public void checkClientTrusted(X509Certificate[] chain, String authType) 43 { 44 } 45 46 @Override 47 public void checkServerTrusted(X509Certificate[] chain, String authType) 48 { 49 } 50 51 @Override 52 public X509Certificate[] getAcceptedIssuers() 53 { 54 return new X509Certificate[]{}; 55 } 56 }}; 57 return trustAllCerts; 58 } 59 60 //获取HostnameVerifier 61 public static HostnameVerifier getHostnameVerifier() 62 { 63 HostnameVerifier hostnameVerifier = new HostnameVerifier() 64 { 65 @Override 66 public boolean verify(String s, SSLSession sslSession) 67 { 68 return true; 69 } 70 }; 71 return hostnameVerifier; 72 } 73 }
有了以上的工具类,通过OKHttpClient.Builder对象调用 “sslSocketFactory ”方法 和 “hostnameVerifier ” 方法。类似于如下:
简言之:
1 builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory()); 2 builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
原文地址:https://www.cnblogs.com/huolongluo/p/8360478.html
时间: 2024-10-03 03:21:25