自定义OKhttp拦截器 添加请求头

来源:互联网 发布:傣族 知乎 编辑:程序博客网 时间:2024/05/16 18:57

新建一个类UserAgentInterceptor实现Interceptor

[html] view plain copy
  1. import java.io.IOException;  
  2. import okhttp3.Interceptor;  
  3. import okhttp3.Request;  
  4. import okhttp3.Response;  
  5.   
  6. /**  
  7.  * 添加请求头  
  8.  */  
  9. public class UserAgentIntercepter implements Interceptor {  
  10.     @Override  
  11.     public Response intercept(Chain chain) throws IOException {  
  12.   
  13.         Request request =  chain.request().newBuilder()  
  14.                 .addHeader("key1","value")  
  15.                 .build();  
  16.   
  17.         return chain.proceed(request);  
  18.     }  
  19. }  

在okhttputils封装类里添加 拦截器

[html] view plain copy
  1. .addInterceptor(new UserAgentIntercepter()) 

原创粉丝点击