在我们的项目开发中很多情况下我们都需要添加自定义的头信息,如token、APP-OS等参数。
一、使用Retrofit2添加请求头
1、使用@Header注解添加请求头
@GET("v2/movie/top250")
Observable<MovieDataBean> getTopMovie(@Header("OS") String os,@Query("start") int start);
就像上面这样,只要在调用的时候传入参数即可,简单方便易操作。
2、使用@HeaderMap注解添加多个请求头
@GET("v2/movie/top250")
Observable<MovieDataBean> getTopMovie(@HeaderMap Map<String,String> headerParams, @Query("start") int start);
二、使用OkHttpClient设置拦截器添加请求头
1、添加拦截器
使用OkHttpClient通过拦截器可以统一设置请求头,不用每个接口都写一遍。
if (App.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
//BODY HEADERS BASIC NONE
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(interceptor);
}
2、自定义拦截器添加请求头
public class MyInterceptor implements Interceptor {
private Context mContext;
public MyInterceptor(Context context) {
this.mContext = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
String method = originalRequest.method();
if (method.equalsIgnoreCase("get")) { //GET请求的参数封装
} else if (method.equalsIgnoreCase("post")) { //POST请求的参数封装
//获取请求Body
RequestBody requestBody = originalRequest.body();
Map<String, String> originalParams = new LinkedHashMap<>();
//requestBody是FormBody对象 即Post请求
if (requestBody instanceof FormBody) {
for (int i = 0; i < ((FormBody) requestBody).size(); i++) {
//将请求参数加入到集合中 统一交给请求头类处理
originalParams.put(((FormBody) requestBody).name(i),
((FormBody) requestBody).value(i));
}
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
String oldParamsJson = buffer.readUtf8();
Gson gson = new Gson();
originalParams = gson.fromJson(oldParamsJson, HashMap.class); //原始参数
}
//处理请求头参数的类
RequestParamsWrapper requestParamsWrapper = new RequestParamsWrapper(originalParams);
originalRequest = originalRequest.newBuilder()
//添加请求头 .headers(requestParamsWrapper.getRequestHeaders(originalRequest.headers()))
.build();
}
return chain.proceed(originalRequest);
}
}