Retrofit常规配置

最近在新项目中集成了retrofit这套网络框架,在这里记录下它的一些常规设置,先列出retrofit的版本依赖及其他依赖,我们知道retrofit的底层网络实现是基于okhttp的,这里我们引用的是最新的okhttp3

compile 'com.squareup.retrofit2:retrofit:2.1.0'

compile 'com.squareup.retrofit2:converter-gson:2.1.0'

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

compile 'com.squareup.okhttp3:okhttp:3.3.1'

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

compile 'io.reactivex:rxandroid:1.1.0'

Log拦截器

这里直接引用okhttp自带的,方法如下

1
2
3
4
5
6
7
8
// log用拦截器
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// 开发模式记录整个body,否则只记录基本信息如返回200,http协议版本等
if (BuildConfig.DEBUG) {
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class HeadInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("app-version", "")
.header("app-device", "")
.header("os-version", "")
.header("phone-model", "")
.header("Accept", "application/json")
.header("User-Agent", "Android/retrofit")
.header("channel", "")
.header("token", "")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}

缓存设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Cache cache=new Cache(FileUtils.getCacheDir(), 50 * 1024 * 1024)//设置50M的文件缓存大小
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetworkUtils.isNetworkAvailable()) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (NetworkUtils.isNetworkAvailable()) {
int maxAge = 0;
// 有网络时 设置缓存超时时间0个小时
response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
response.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return chain.proceed(request);
}
}

公共参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CommonParameterInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
HttpUrl modifiedUrl = originalRequest.url().newBuilder()
// Provide your custom parameter here
.addQueryParameter("token", "")
.addQueryParameter("app_version", "1.0.0")
//...
.build();
Request request = originalRequest.newBuilder().url(modifiedUrl).build();
return chain.proceed(request);
}
}

最后看完整的设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = getBuilder().client(getHttpClient()).build();
return retrofit.create(serviceClass);
}
private Retrofit.Builder getBuilder() {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
return builder;
}
private OkHttpClient getHttpClient() {
// log用拦截器
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// 开发模式记录整个body,否则只记录基本信息如返回200,http协议版本等
if (BuildConfig.DEBUG) {
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
}
return new OkHttpClient.Builder()
.addInterceptor(logging)
.addInterceptor(new HeadInterceptor())
.addInterceptor(new CacheInterceptor())
.addInterceptor(new CommonParameterInterceptor())
.cache(new Cache(FileUtils.getCacheDir(), 10 * 1024 * 1024))
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
})
.build();
}

参考

http://wuxiaolong.me/2016/06/18/retrofits/
http://zhaoshanshan.me/2015/10/12/Retrofit2-%E6%9B%B4%E6%96%B0%E6%8C%87%E5%8D%97/