联网请求统一加上header

我使用的联网框架是okhttp,要加上header,在初始化的时添加一个拦截器
OkHttpClient.Builder builder = new OkHttpClient.Builder();
mOkHttpClient = builder
.retryOnConnectionFailure(true)//连接失败时自动重连
.addInterceptor(new TokenInterceptor())
.connectTimeout(10, TimeUnit.SECONDS) //设置连接网络超时时间,单位是秒
.readTimeout(20, TimeUnit.SECONDS) //读取数据超时时间
.writeTimeout(20, TimeUnit.SECONDS)//写入数据超时时间
.build(); //缓存和拦截器如果没有需求就不用添加

   public class TokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    Request authorised = originalRequest.newBuilder()
            .header("Content Type","application/json")
            .build();
    return chain.proceed(authorised);

}
}    

你可能感兴趣的:(联网请求统一加上header)