使用retrofit2.0时,当url是https开头的时候,会报证书认证的异常。
项目中使用下信任所有证书,解决了这个问题
具体是:
public class SCApplication extends Application {
private static final String TAG = "SCApplication";
private static SCApplication mApplication;
public static synchronized SCApplication getApplicationInstance() {
if (mApplication == null) {
mApplication = new SCApplication();
}
return mApplication;
}
@Override
public void onCreate() {
super.onCreate();
mApplication = this;
}
主要是给okhttpclient设置证书 使用下面方法信任所有证书
/**
* 获取Https的证书
*
* @param context Activity(fragment)的上下文
* @return SSL的上下文对象
*/
private static SSLContext getSSLContext(Context context) {
SSLContext s_sSLContext;
try {
s_sSLContext = SSLContext.getInstance("TLS");
//信任所有证书 (官方不推荐使用)
s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
}}, new SecureRandom());
return s_sSLContext;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
然后在retrofit初始化的时候设置进去
SSLContext sslContext = getSSLContext(SCApplication.getApplicationInstance().getApplicationContext());
OkHttpClient client=new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(20, TimeUnit.SECONDS)//设置写入超时时间
.addInterceptor(InterceptorUtil.HeaderInterceptor())//添加其他拦截器
.addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器
.sslSocketFactory(sslContext.getSocketFactory()) //添加证书
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create()) //添加Gson转换器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加Rx转换器
.baseUrl(ApiServise.API_SERVER_URL) //baseurl
.client(client)
.build();
这样就能正常请求数据了,本人亲测有用。