OkHttp3 Interceptor 拦截器的使用 统一追加参数
2017-05-20 23:55
344 查看
日志拦截器
添加依赖compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
设置
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(httpLoggingInterceptor);
Get请求统一追加参数
public class AppendUrlParamInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //拿到有信息的buidler HttpUrl.Builder builder = request.url().newBuilder(); //得到新的Url(已经追加好了参数) HttpUrl newUrl = builder .addQueryParameter("token", "iamtoken") .build(); //利用新的Url 构建新的Request ,并发送给服务器 Request newRequest = request.newBuilder() .url(newUrl) .build(); return chain.proceed(newRequest); } }
Header统一追加参数
public class AppendHeaderParamInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //核心也是通过newBuilder 拿到Builder Headers.Builder builder = request. headers(). newBuilder(); //统一追加header参数 Headers newHeader = builder .add("header1", "iam header1") .build(); Request newRequest = request.newBuilder() .headers(newHeader) .build(); return chain.proceed(newRequest); } }
Post请求body统一追加参数
public class AppenBodyParamsInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //构建新Body RequestBody newBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded") , "token=iamtoken"); Request newRequest = request.newBuilder() .post(newBody) .build(); return chain.proceed(newRequest); } }
相关文章推荐
- OKHttp使用拦截器(Interceptor)POST与GET方法,统一封装传公共参数
- Rx系列学习笔记_使用okhttp拦截器统一处理返回请求
- OkHttp的基本使用-3(添加拦截器和GET请求的参数拼接)
- android,retrofit,okhttp,日志拦截器,使用拦截器Interceptor统一打印请求与响应的json
- retrofit2.0使用拦截器Interceptor统一打印请求与响应的json
- retrofit2.0使用拦截器Interceptor统一打印请求与响应的json
- 关于在struts2中interceptor 中使用ActionInvocation 对象获得HttpServletRequest中封装的参数,以Map的形式
- 解决struts2使用拦截器后参数无效问题
- 在struts2中使用拦截器(Interceptor)控制登录和权限
- struts2 Interceptor(拦截器)中获取HTTP 参数的方法
- VCL定义和使用CM_Message的原因(主要是内部控制,同时可简化参数传递,还可截住消息,统一走消息路线,还可省内存)
- Struts2默认拦截器(ExceptionMappingInterceptor)的使用及源码阅读
- struts2技巧与解惑——使用包(package)和拦截器(interceptor)分配和处理权限
- 在struts中使用拦截器(Interceptor)控制登录和权限
- Struts2默认拦截器(ExceptionMappingInterceptor)的使用及源码阅读
- Struts 拦截器interceptor 的使用
- struts2拦截器使用(用户session失效后的统一页面指向)
- Struts2拦截器(Interceptor)的使用范例
- 在struts2中使用拦截器(Interceptor)控制登录和权限
- struts2拦截器使用(用户session失效后的统一页面指向)