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 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的可以直接去掉

你可能感兴趣的:(android入门教学,工具类,android基础)