okHttp跳过强制https验证
okHttp是基于client连接的,所有的网络连接https都要遵循几次握手才能数据相互传输,因为https的单向或者双向加密的,所以要想访问,就需要ssl证书。
对于想用他爬取一些网络数据以及模拟登陆一些网站的时候,https很大的程度加深了我们项目开发的难度,因为要匹配https。
那么对于我们并不是要开发我们公司或者自己的客户端,而是爬取或者登陆别人的网站的时候,我们大多数是不需要https的,大多数提供https的网站,是可以直接拿到网页源码等的,但是在有些网站开启了强制https验证的时候,我们如果直接访问https,就会访问出错。
那么需要我们重写okhttp提供的sslSocketFactory和hostnameVerifier类来伪造一个证书达到绕过https验证的方法。
方法1
---------------------
1 private static OkHttpClient getUnsafeOkHttpClient() { 2 try { 3 // Create a trust manager that does not validate certificate chains 4 final TrustManager[] trustAllCerts = new TrustManager[]{ 5 new X509TrustManager() { 6 @Override 7 public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { 8 } 9 10 @Override 11 public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { 12 } 13 14 @Override 15 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 16 return new java.security.cert.X509Certificate[]{}; 17 } 18 } 19 }; 20 21 // Install the all-trusting trust manager 22 final SSLContext sslContext = SSLContext.getInstance("SSL"); 23 sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); 24 // Create an ssl socket factory with our all-trusting manager 25 final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); 26 27 OkHttpClient.Builder builder = new OkHttpClient.Builder(); 28 builder.sslSocketFactory(sslSocketFactory); 29 builder.hostnameVerifier(new HostnameVerifier() { 30 @Override 31 public boolean verify(String hostname, SSLSession session) { 32 return true; 33 } 34 }); 35 OkHttpClient okHttpClient = builder.build(); 36 return okHttpClient; 37 } catch (Exception e) { 38 throw new RuntimeException(e); 39 } 40 }
方式2
1 X509TrustManager xtm = new X509TrustManager() { 2 @Override 3 public void checkClientTrusted(X509Certificate[] chain, String authType) { 4 } 5 6 @Override 7 public void checkServerTrusted(X509Certificate[] chain, String authType) { 8 } 9 10 @Override 11 public X509Certificate[] getAcceptedIssuers() { 12 X509Certificate[] x509Certificates = new X509Certificate[0]; 13 return x509Certificates; 14 } 15 }; 16 17 SSLContext sslContext = null; 18 try { 19 sslContext = SSLContext.getInstance("SSL"); 20 21 sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom()); 22 23 } catch (NoSuchAlgorithmException e) { 24 e.printStackTrace(); 25 } catch (KeyManagementException e) { 26 e.printStackTrace(); 27 } 28 HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 29 @Override 30 public boolean verify(String hostname, SSLSession session) { 31 return true; 32 } 33 }; 34 OkHttpClient okHttpClient = new OkHttpClient.Builder() 35 .addInterceptor(interceptor) 36 .sslSocketFactory(sslContext.getSocketFactory()) 37 .hostnameVerifier(DO_NOT_VERIFY) 38 .build();
原文:https://blog.csdn.net/applek_case/article/details/79374219
【做一朵向日葵,面朝太阳,心纳阳光。心,只要有了充盈的阳光,就不再那么的冰;人,也就不再那么的冷;拥有了热度,心也跟着有了温度。】