OkHttp 忽略安全证书及其调用

package com.http.util;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @author yxj
 * @created 2019-02-13 14:23
 * @description
 */

public class SSLSocketClient {

    
    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);
        }
    }

    
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

   
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }


}

调用(post json): 

    private void sendPostJson(String auth, String url, String json) {
        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        System.out.println(body.toString());
        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())//调用
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())//调用
                .build();
        Request request = new Request.Builder()
                .addHeader("Accept", "application/json")
                .addHeader("Content-Length", "256")
                .addHeader("Authorization", auth)
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .post(body)
                .url(url)
                .build();

        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response);
            if (response.isSuccessful()) {
                String res = response.body().string();
                System.out.println(res);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

最近对接第三方接口,和平时遇到的不太一样,这样一顿操作之后就好了

你可能感兴趣的:(util,note,java)