之前已经讲过了Retrofit2.0的初步认识,不是很清楚的同学可以参看我的文章链接:
Retrofit2.0初识:http://blog.csdn.net/burn_yourself/article/details/71799253
一般的,我们在写网络通讯的时候,log调试是必须的,那么本篇文章就来讲讲 Retrofit2.0 和 它的 拦截器们,主要包括以下几方面:
1. Header 拦截器
2. Cache 拦截器
3.log 拦截器
那么,下面就一一讲述添加。
首先,还是需要添加网络权限,由于缓存拦截器,涉及到网络状态,于是还要多添加一个网络状态权限,本篇涉及到的权限有:
app 的 gradle 中添加包的引用:
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
注意,由于retrofit2.0 本身就是对okhttp3的一个封装,所以不必再添加对于okhttp3.X 的引用
由于Retrofit2.0中并没有对于拦截器的处理,于是还是得在 OKhttp 中去处理拦截的问题,然后将 okhttp 对象 add 到 Retrofit 初始化的代码中。
大概思路如此,首先贴出 Retrofit2.0 通讯大致流程,还是以 retrofit2.0 中 获取短信验证码为例:
1.声明api:
public interface ApiService
//注册时获取短信验证码
@POST("api/login/pushSms")
@FormUrlEncoded
Call
}
2.写Retrofit对象,并配置网络:
package com.test.http.retrofit;
import com.test.http.interceptor.CacheInterceptor;
import com.test.http.interceptor.HeaderInterceptor;
import com.test.util.LogUtil;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Admin on 2017/5/12.
*/
public class HttpClient{
public ApiService mApiService;
private HttpClient() {
Cache cache = new Cache(new File(BuildConfig.PATH_CACHE), BuildConfig.DEFAULT_CACHE_SIZE);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor())//设置Header
.addNetworkInterceptor(new CacheInterceptor())//设置缓存
.addInterceptor(new CacheInterceptor())
.cache(cache)
.connectTimeout(BuildConfig.DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(BuildConfig.DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(BuildConfig.DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
.retryOnConnectionFailure(true);//错误重连
//调试模式打印Log日志
if (BuildConfig.DEBUG) {
builder.addInterceptor(new LoggingInterceptor());
}
OkHttpClient client=builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
mApiService = retrofit.create(ApiService.class);
}
private static class HttpClientHolder {
private static final HttpClient INSTANCE = new HttpClient();
}
public static HttpClient getInstance() {
return HttpClientHolder.INSTANCE;
}
public ApiService getApiService() {
return mApiService;
}
}
activity中调用与接收:
private void send(Map
HttpClient.getInstance().getApiService().postSms(map).enqueue(new Callback
@Override
public void onResponse(Call
int code=response.code();
ApiResponse apiResponse=response.body();
SmsCode sms= (SmsCode) apiResponse.getData();
Log.e(TAG, "sms: "+sms.getStatus());
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e(TAG, "t"+t.getMessage());
}
});
}
大家细心的话会发现 类 HttpClient 中已经添加得有 拦截器了,HeaderInterceptor,CacheInterceptor,LoggingInterceptor.
拦截器都要实现 Interceptor 接口,首先看 HeaderInterceptor 是怎么实现的
/**
* Created by Admin on 2017/5/13.
* header拦截器,对Header统一处理,涉及到header加密的也在此处理
*/
public class HeaderInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//处理业务逻辑,可以对header统一处理,涉及到header加密的也在此处理
//......
request = builder.build();
return chain.proceed(request);
}
}
然后介绍的是 CacheInterceptor :
package com.test.http.interceptor;
import com.test.http.retrofit.BuildConfig;
import com.test.util.NetUtil;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Administrator on 2016/11/3.
* 缓存拦截器
*/
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetUtil.isNetworkConnected()) {//没网强制从缓存读取(必须得写,不然断网状态下,退出应用,或者等待一分钟后,就获取不到缓存)
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (NetUtil.isNetworkConnected()) {//有网情况下,从服务器获取
int maxAge = BuildConfig.DEFAULT_COOKIE_NETWORK_TIME;
// 有网络时, 缓存最大保存时长为60s
response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.removeHeader("Pragma")
.build();
} else {//没网情况下,一律从缓存获取
// 无网络时,设置超时为30天
int maxStale = BuildConfig.DEFAULT_COOKIE_NO_NETWORK_TIME;
response.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.removeHeader("Pragma")
.build();
}
return response;
}
}
最后介绍我们的 LoggingInterceptor,其实个人认为 LoggingInterceptor 还是比较重要的,Retrofit2.0 中log拦截器的实现有两种方式,一种是自定义,另一种是调用 okhpp中自带的 log拦截器,
那么,先介绍 LoggingInterceptor 的实现:
/**
* Created by Admin on 2017/5/13.
* 自定义log打印拦截器
*/
public class LoggingInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
//这个chain里面包含了request和response,所以你要什么都可以从这里拿
//=========发送===========
Request request = chain.request();
long requestTime = System.currentTimeMillis();//请求发起的时间
HttpUrl requestUrl=request.url();
Connection requestConnection=chain.connection();
Headers requestHeaders=request.headers();
//打印发送信息
LogUtil.e("===LoggingInterceptor===发送==requestUrl="+requestUrl);
LogUtil.e("===LoggingInterceptor===发送==requestConnection="+requestConnection);
LogUtil.e("===LoggingInterceptor===发送==requestHeaders="+requestHeaders);
//=========接收===========
long responseTime = System.currentTimeMillis();//收到响应的时间
Response response = chain.proceed(chain.request());
ResponseBody responseBody = response.peekBody(1024 * 1024);
HttpUrl responseUrl=response.request().url();
String content = response.body().string();
Headers responseHeaders=response.headers();
long delayTime=responseTime-requestTime;
//打印接收信息
LogUtil.e("=====LoggingInterceptor===接收==responseUrl="+responseUrl);
LogUtil.e("=====LoggingInterceptor===接收==responseHeaders="+responseHeaders);
LogUtil.e("=====LoggingInterceptor===接收==delayTime="+delayTime);
LogUtil.e("=====LoggingInterceptor===接收==content="+content);
return response;
}
}
这里最需要注意的是 方法中 对 request 和 response 的获取和处理
自定义 Log调试类在 HttpClient 中的调用顺序是 ,先对 okhttp。builder 做些其它基本配置,然后
调试模式打印Log日志
if (BuildConfig.DEBUG) {
builder.addInterceptor(new LoggingInterceptor());
}
最后,在retrofit中加入 okhttp对象
OkHttpClient client=builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
mApiService = retrofit.create(ApiService.class);
OKHttp 调用系统 Log打印的话,需要在 app。gradle 中添加引用:
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
然后在代码中这样写:
//调用系统log拦截器
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(
new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
LogUtil.e("=======message=="+message);
}
});
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
message中会打印出 通讯中各种详细信息。
最后,贴出 网络配置文件代码:
/**
* Created by Admin on 2017/5/12.
* 网络通讯相关配置
*/
public class BuildConfig {
public static boolean DEBUG=true;
/**正试**/
private final static String RELEASE_URL = "";
/**测试**/
private static final String DEBUG_URL = "http://192.168.0.10/";
public final static String BASE_URL = BuildConfig.DEBUG ? DEBUG_URL : RELEASE_URL;
public static final int DEFAULT_CACHE_SIZE = 150 * 1024 * 1024; // 50 MiB
/*超时时间-默认10秒*/
public static final int DEFAULT_CONNECT_TIMEOUT = 20;
public static final int DEFAULT_READ_TIMEOUT = 20;
public static final int DEFAULT_WRITE_TIMEOUT = 20;
/*有网情况下的本地缓存时间默认60秒*/
public static final int DEFAULT_COOKIE_NETWORK_TIME = 0;
/*无网络的情况下本地缓存时间默认30天*/
public static final int DEFAULT_COOKIE_NO_NETWORK_TIME = 24 * 60 * 60 * 30;
public static final String PATH_DATA = MyApplication.getInstance().getCacheDir().getAbsolutePath() + File.separator + "data";
public static final String PATH_CACHE = PATH_DATA + "/NetCache";
}
OK,今天关于 Retrofit2.0 拦截器就讲到这里,睡觉去了。大家有什么疑问,或者我理解得有误的地方,欢迎交流