在实际项目中,对于有需要统一进行公共参数添加的网络请求,可以使用下面的代码来实现:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ctx).setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addQueryParam("publicParams", "1");
}
}).setConverter(new BaseConverter())
.build();
在RestAdapter的实例化对象的时候,为其指定一个RequestInterceptor接口的实现类即可,在该类中,可以对请求体的相关参数进行设置,如addHeader、addQueryParam等。
不过遗憾的是Retrofit2.0已经没有了该类,该怎么做呢?通过Interceptor实现。
Interceptor是拦截器, 在发送之前, 添加一些参数, 或者获取一些信息。
/**
* 封装公共参数(Key和密码)
* <p>
*/
public class CommonInterceptor implements Interceptor {
private final String mApiKey;
private final String mApiSecret;
public CommonInterceptor(String apiKey, String apiSecret) {
mApiKey = apiKey;
mApiSecret = apiSecret;
}
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
String marvelHash = ApiUtils.generateMarvelHash(mApiKey, mApiSecret);
Request oldRequest = chain.request();
// 添加新的参数
HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host())
.addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey)
.addQueryParameter(MarvelService.PARAM_TIMESTAMP, ApiUtils.getUnixTimeStamp())
.addQueryParameter(MarvelService.PARAM_HASH, marvelHash);
// 新的请求
Request newRequest = oldRequest.newBuilder()
.method(oldRequest.method(), oldRequest.body())
.url(authorizedUrlBuilder.build())
.build();
return chain.proceed(newRequest);
}
}
Okhttp3使用了装饰者模式, 使用Builder添加Interceptor。
CommonInterceptor commonInterceptor = new CommonInterceptor(
"key", "Secret");
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(commonInterceptor)
.build();
// 适配器
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
网友评论