您的位置:首页 > 理论基础 > 计算机网络

Android开发-----关于解决Retrofit打印HttpLog和设置连接超时的问题

2017-04-11 16:00 645 查看

问题,

1 由于Retrofit默认连接超时时间只有10s 某些情况下可能连接时间会超过10s,这个时候就会报出SocketTimeoutException 这个时候我们就需要自己设置超时间,


2 很多时候需要查看自己请求的网络地址,或者请求参数,当然也可以借助抓包工具,通过OKHttp自带的可以支持打印Log,我们在控制台就可以看见请求信息或返回的数据,也不需要另外开工具,也还是比较方便。

解决办法

针对这2个问题写了一个工具类仅供参考,

需要打印Http请求地址等信息需要添加Gradle引用

compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
Retrofit默认支持OkHttp 所以不需要再额外添加。

工具类如下。

/**
* [description about this class]
*
* @author zhangqil
* @DATE 2017-04-11 15:21
* @copyright Copyright 2010 RD information technology Co.,ltd.. All Rights Reserved.
*/
public class RetrofitUtils {
private static RetrofitUtils mOkHttpUtils;
//解决优化查询超时问题 默认10s
private static final int DEFAULT_TIMEOUT = 30; //此处默认超时时间为30s
private TimeUnit mTimeUnitSECONDS = TimeUnit.SECONDS;
private OkHttpClient.Builder build = new OkHttpClient.Builder();

private RetrofitUtils() {
}

public static RetrofitUtils getInstance() {
if (mOkHttpUtils == null) {
mOkHttpUtils = new RetrofitUtils();
}
return mOkHttpUtils;
}

public OkHttpClient build() {
return build.build();
}

/***
* 添加超时时间
*
* @param timeOut 超时时间 单位秒
* @return
*/
public RetrofitUtils addTimeOut(int timeOut) {
if (timeOut <= 0) timeOut = DEFAULT_TIMEOUT;
build.connectTimeout(timeOut, mTimeUnitSECONDS)
.writeTimeout(timeOut, mTimeUnitSECONDS)
.readTimeout(timeOut, mTimeUnitSECONDS);
return this;
}

/***
* 添加http请求log 包括请求url 请求参数 返回的参数 等信息。
*
* @return
*/
public RetrofitUtils addHttpLog() {
//日志显示级别
HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
if (BuildConfig.DEBUG) {
Log.i("httpLog", "message:" + message);
}
}
});
loggingInterceptor.setLevel(level);
//OkHttp进行添加拦截器loggingInterceptor
build.addInterceptor(loggingInterceptor);
return this;
}

}

如何使用:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(You BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //此处是添加Rxjava支持
.addConverterFactory(GsonConverterFactory.create()) //添加Gson支持
.client(RetrofitUtils.getInstance().addTimeOut(30).addHttpLog().build()) //构建自己的OkHttpClient
.build();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐