1. 程式人生 > >Okhttp3信任所有證書設定

Okhttp3信任所有證書設定

/**
 * 預設信任所有的證書
 * TODO 最好加上證書認證,主流App都有自己的證書
 *
 * @return
 */
@SuppressLint("TrulyRandom")
private static SSLSocketFactory createSSLSocketFactory() {
    SSLSocketFactory sSLSocketFactory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new
TrustAllManager()}, new SecureRandom()); sSLSocketFactory = sc.getSocketFactory(); } catch (Exception e) { } return sSLSocketFactory; } private static class TrustAllManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws
CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } private static class
TrustAllHostnameVerifier implements HostnameVerifier {
@Override public boolean verify(String hostname, SSLSession session) { return true; } }

OkHttp配置

  //log攔截器 列印所有的log
  HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
      @Override
      public void log(String message) {
          LogUtils.e("HttpLog",message);
      }
  });
  loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  //初始化OkHttp
  OkHttpClient client = new OkHttpClient.Builder()
          .connectTimeout(NetworkConfig.ConnectionTime, TimeUnit.SECONDS)
          .addInterceptor(new RetryIntercepter(3))  //新增自定義攔截
          .addInterceptor(loggingInterceptor)
          .sslSocketFactory(createSSLSocketFactory())
          .hostnameVerifier(new TrustAllHostnameVerifier())
          .build();
  //初始化 retrofit
  Retrofit retrofit = new Retrofit.Builder()
          .addConverterFactory(GsonConverterFactory.create())
          .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
          .client(client)
          .baseUrl(baseUrl)
          .build();