okhttp添加公共参数 添加统一参数 okhttp4.2添加公共参数 添加统一参数

最近遇到的一个问题就是:所有请求接口都要增加一个token参数… 并且token参数有可能过期。

庆幸的是,Okhttp提供了强大的拦截器功能,是一种能够监控,重写,重试调用的强大机制

比如微信  APP登录   

{
"errcode":40029,"errmsg":"invalid code"
}
public class WXTokenInterceptord implements Interceptor {

     private final String TAG = "wx";

     @Override
     public Response intercept(Chain chain) throws IOException {
           Request request = chain.request()
                                .newBuilder()
                                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                                .addHeader("Accept-Encoding", "gzip, deflate")
                                .addHeader("Connection", "keep-alive")
                                .addHeader("Accept", "*/*")
                                .addHeader("Cookie", "add cookies here")
                                   .build();
        // 新的请求,添加参数
         Request newRequest = addParam(request );

         return chain.proceed(request);;
     }
 /**
      * 添加公共参数
      *
      * @param oldRequest
      * @return
      */
     private Request addParam(Request oldRequest) {

         HttpUrl.Builder builder = oldRequest.url()
                 .newBuilder()
                 .setEncodedQueryParameter("xx", "xxx");

         Request newRequest = oldRequest.newBuilder()
                 .method(oldRequest.method(), oldRequest.body())
                 .url(builder.build())
                 .build();

         return newRequest;
     }
 
     
 }

然后为OkHttp配置一个拦截器。

 

 

public static OkHttpClient getOkHttpClient() {
        Interceptor interceptor = new WXTokenInterceptord ();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .addInterceptor(interceptor)
                .addInterceptor(new HttpLoggingInterceptor(new MyLog()).setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        return client;
    }
 

 

你可能感兴趣的:(okhttp添加公共参数 添加统一参数 okhttp4.2添加公共参数 添加统一参数)