zoukankan      html  css  js  c++  java
  • OkHttpClient跳过证书验证

    package com.example.test.utils;
    
    import javax.net.ssl.*;
    import java.security.KeyStore;
    import java.security.SecureRandom;
    import java.security.cert.X509Certificate;
    import java.util.Arrays;
    
    public class SSLSocketClient {
    
        /**
         * 获取这个SSLSocketFactory
         * */
        public static SSLSocketFactory getSSLSocketFactory() {
            try {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, getTrustManager(), new SecureRandom());
                return sslContext.getSocketFactory();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 获取TrustManager
         * */
        private static TrustManager[] getTrustManager() {
            return new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }
    
                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }
    
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };
        }
    
        /**
         * 获取HostnameVerifier
         * */
        public static HostnameVerifier getHostnameVerifier() {
            return (s, sslSession) -> true;
        }
    
        public static X509TrustManager getX509TrustManager() {
            X509TrustManager trustManager = null;
            try {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init((KeyStore) null);
                TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
                if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                    throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
                }
                trustManager = (X509TrustManager) trustManagers[0];
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return trustManager;
        }
    
    }

    调用

    public static HashMap httpPost(String url, HashMap<String, Object> data, String token) throws IOException {
            HashMap<String, Object> result = new HashMap<>();
            if ("".equals(url)) {
                return result;
            }
            OkHttpClient client = new OkHttpClient.Builder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .build();
    
            MediaType mediaType = MediaType.parse("application/json;charset=utf8");
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(data));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("content-type", "application/json")
                    .addHeader("X-Auth-Token", token)
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            String getToken = response.header("X-Subject-Token");
            HashMap res = JSON.parseObject(responseData, HashMap.class);
            result.put("token", getToken);
            result.put("res", res);
            return result;
        }
  • 相关阅读:
    Subversion版本控制系统的安装和操作.
    java基础
    iOS_第3方类库MBprogressHUD
    wikioi 1396 伸展树(两个模板)
    从乐视和小米“最火电视”之战 看PR传播策略
    Android开发之大位图压缩水印处理
    Spark SQL with Hive
    PHP设计模式——模板模式
    Nginx 配置 gzip 压缩
    SecureCRT学习之道:SecureCRT 经常使用技巧
  • 原文地址:https://www.cnblogs.com/todarcy/p/15104125.html
Copyright © 2011-2022 走看看