Android http请求中,通常每个request都有相同的参数,比如,token,uid等等,如何能一次性封装这些重复参数呢
本文的目的就是解决重复封装的梗,而解决这个问题的主要助手就是Interceptor(拦截器)
- 自定义Interceptor
public class BaseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
//添加请求参数,此处是以豆瓣api为例,下面会贴出Base_url
HttpUrl url=original.url().newBuilder()
.addQueryParameter("count", "5")
.addQueryParameter("start", "0")
.build();
//添加请求头
Request request = original.newBuilder()
.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.addHeader("Connection", "keep-alive")
.method(original.method(), original.body())
.url(url)
.build();
return chain.proceed(request);
}}
- 使用BaseInterceptor
public static final String BASE_URL = "https://api.douban.com/v2/movie/";
//此类Http工具类
public HttpClient() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(5, TimeUnit.SECONDS);
client.addInterceptor(new BaseInterceptor());
retrofit = new Retrofit.Builder().
baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
service = retrofit.create(MovieService.class);
}
-
//此类 retrofit api service
public interface MovieService {
@POST("in_theaters")
Observable<BaseResponse<List<MovieResponse>>> getMovie();
}