• OkHttp3.1以上信任所有证书,OkHttpClient设置忽略所有SSL证书验证


    在开发中个,第三方https-ssl是自建的,在使用OKhttp/restTemplate调用是报错:

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
    

      

    OkHttpClient设置忽略所有SSL证书验证

    Okhttp代码

    public static OkHttpClient getUnsafeOkHttpClient() {
            try {
                // Create a trust manager that does not validate certificate chains
                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[]{};
                            }
                        }
                };
     
                // Install the all-trusting trust manager
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                // Create an ssl socket factory with our all-trusting manager
                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;
                    }
                });
     
                OkHttpClient okHttpClient = builder.build();
                return okHttpClient;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    

      

    写了个工具类

    import okhttp3.MediaType;
    import okhttp3.OkHttpClient;
    
    import javax.net.ssl.*;
    import java.util.concurrent.TimeUnit;
    
    public class OkHttpClintUtil {
    
        public static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    
        /**
         * 默认-不信任自建ssl
         */
        public static final OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                .build();
    
    
        /**
         * 信任所有https-ssl证书
         * 航信https-ssl证书是自建的(无耻,不舍得花钱购买)
         * @return
         */
        public static OkHttpClient getUnsafeOkHttpClient() {
            try {
                // Create a trust manager that does not validate certificate chains
                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[]{};
                            }
                        }
                };
    
                // Install the all-trusting trust manager
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                // Create an ssl socket factory with our all-trusting manager
                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;
                    }
                });
    
                OkHttpClient okHttpClient = builder
                        .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                        .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                        .build();
                return okHttpClient;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
    
    
    
    }
    

      

    调用:

    Map<String, Object> params = new HashMap<>();
            params.put("username", TRAVELSKY_BAGGAGE_U);
            params.put("password", TRAVELSKY_BAGGAGE_P);
            String param= JSON.toJSONString(params);
            RequestBody requestBody = RequestBody.create(OkHttpClintUtil.mediaType, param);
    
    
            Request getUserRequest = new Request.Builder().url(TRAVELSKY_BAGGAGE_URL)
                    .post(requestBody).build();
    
     Response userResponse = OkHttpClintUtil.getUnsafeOkHttpClient().newCall(getUserRequest).execute();
               
    

      

    restTemplate

    @Bean
        public RestTemplate restTemplate(){
            return new RestTemplateBuilder().build();
        }
        /**
         * HTTPS RestTemplate
         */
        @Bean
        public RestTemplate httpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    
            CloseableHttpClient httpClient
                    = HttpClients.custom()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .setSSLSocketFactory(sslConnectionSocketFactory)
                    .build();
            HttpComponentsClientHttpRequestFactory requestFactory
                    = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(httpClient);
            requestFactory.setConnectTimeout((int) Duration.ofSeconds(5).toMillis());
            return new RestTemplate(requestFactory);
        }
    

      

  • 相关阅读:
    【IDE_IntelliJ IDEA】idea主题设置
    【IDE_IntelliJ IDEA】idea中设置类和方法的注释模板
    【前端_css】RGB 常用颜色列表
    【IDE_IntelliJ IDEA】IDEA中使用Junit插件自动创建测试用例到test目录
    【DB_MySQL】MySQL日志分析
    【IDE_IntelliJ IDEA】IDEA 创建类注释模板和方法注释模板
    【前端_js】ES6原生提供的Promise 对象。
    【Java_基础】Java中强制类型转换
    【IDE_IntelliJ IDEA】在Intellij IDEA中使用Debug
    使用反射来编写实体类的XML
  • 原文地址:https://www.cnblogs.com/achengmu/p/15094311.html
Copyright © 2020-2023  润新知