1. 程式人生 > >OKhttp忽略https證書

OKhttp忽略https證書

遇到坑公司兩個網自動匹配錯了一直報   D/NetworkSecurityConfig: No Network Security Config specified, using platform default

老費勁 記錄下

到入工具類SSLSocketClient :

import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by liutao on 2018/8/9.
 */

public class SSLSocketClient {
    //獲取這個SSLSocketFactory
    //通過這個類我們可以獲得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() {
        //不校檢證書鏈
        TrustManager[] trustAllCerts = 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[]{};
                        //OKhttp3.0以前返回null,3.0以後返回new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    //獲取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                //未真正校檢伺服器端證書域名
                return true;
            }
        };
        return hostnameVerifier;
    }
}

okhttp工具類:

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by liutao on 2017/9/21.
 */

public class MyOkHttpUtils {
    //mdiatype 這個需要和服務端保持一致
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

    public static final String BaseUrl="https://192.168.11.11:9101";   //公司伺服器

    public static OkHttpClient okHttpClient=null;

    static String cookies;

    //懶漢
    private static synchronized OkHttpClient getInstance(){


         okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .sslSocketFactory(new SSLSocketClient().getSSLSocketFactory())//配置
                .hostnameVerifier(new SSLSocketClient().getHostnameVerifier())//配置    //忽略驗證證書
                .build();

        if(okHttpClient==null){
            okHttpClient=new OkHttpClient();
        }

        cookies=SharedPreferencesUtils.getString("cookie");
        return  okHttpClient;
    }

    /**
     * OKHttp 同步 Get
     *
     * @param url 請求網址
     * @return 獲取到資料返回Response,若未獲取到資料返回null
     *
     * 我們希望以非同步的方式去執行請求,呼叫的是call.enqueue,將call加入排程佇列,然後等待任務執行完成,我們在Callback中即可得到結果。
     */

    public static Response okHttpGet(String url){
        getInstance();

        Request request=new Request.Builder().addHeader("cookie",cookies).url(url).build();

        Response response=null;

        try {
            response=okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return response;

    }

    /**
     * OKHttp 非同步 Post
     *
     * @param url 請求網址
     * @return 獲取到資料返回Response,若未獲取到資料返回null
     */
    public static Response okHttpPost(String url, HashMap<String,String> paramsMap){

        getInstance();



        FormBody.Builder builder = new FormBody.Builder();

        for(String key:paramsMap.keySet()){
            builder.add(key,paramsMap.get(key));
        }

        RequestBody requestBody=builder.build();

        Request request=new Request.Builder().addHeader("cookie",cookies).url(url).post(requestBody).build();

        Response response=null;

        try {
            response=okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return response;

    };
}

不要要使用cookies的可以直接去掉