Retrofit2.0+OkHttp设置统一的请求头(request headers)

时间:2022-05-31 00:37:25

有时候要求Retrofit2的接口中每个都要增加上headers,又不想做重复的事情,可以使用这种方法来为每个request请求都设置上相同的请求头header。

修改请求头request headers主要是通过拦截器来实现,下面是我自己根据需要设置的。如果还有增加其他的header,可以再进行增加。

 /**
* 请求拦截器,修改请求header
*/
private class RequestInterceptor implements Interceptor{ @Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "text/html; charset=UTF-8")
// .addHeader("Accept-Encoding", "*")
.addHeader("Connection", "keep-alive")
.addHeader("Accept", "*/*")
.addHeader("Access-Control-Allow-Origin", "*")
.addHeader("Access-Control-Allow-Headers", "X-Requested-With")
.addHeader("Vary", "Accept-Encoding")
// .addHeader("Cookie", "add cookies here")
.build(); Log.v("zcb", "request:" + request.toString());
Log.v("zcb", "request headers:" + request.headers().toString()); return chain.proceed(request);
}
}

使用方法:

    private OkHttpClient getOkHttpClient() {
//定制OkHttp
OkHttpClient.Builder httpClientBuilder = new OkHttpClient
.Builder();
//设置超时时间
httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClientBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//使用拦截器
httpClientBuilder.addInterceptor(new RequestInterceptor());
httpClientBuilder.addInterceptor(new LogInterceptor()); return httpClientBuilder.build();
}