使用场景

在我们实际的开发中, 比如有很多接口都需要传递版本号, 参数的签名的校验信息, token 信息, 请求头信息等等, 那么我们就可以使用 OKHttp 添加拦截器的方式进行公共参数的添加

使用方式

构建 OKHttpClient 可自定义添加拦截器, 贴出重要部分代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor()) // Token 处理的拦截器
                .addInterceptor(new SingInterceptor()) // 签名校验的拦截器处理
                .addInterceptor(new CommonParamsInterceptor()) // 公共参数拦截器
                /*添加拦截器, 设置打印日志的级别*/
                .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        LogUtil.e("http-->  ", message);
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ApiServer.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();


}

几种添加拦截器的方式

  1. POST 请求添加 RequestBody 添加公共参数, JSON 的 POST 请求

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
    
        if (request.body() instanceof RequestBody) {
    
            RequestBody body = request.body();// 得到请求体
            Buffer buffer = new Buffer();// 创建缓存
            body.writeTo(buffer);//将请求体内容,写入缓存
            String parameterStr = buffer.readUtf8();// 读取参数字符串
    
             // 添加公共参数
            JsonObject jsonObject = GsonUtils.fromJson(parameterStr, JsonObject.class);
            jsonObject.addProperty("reqId", ParamsUtil.INSTANCE.getReqId());
            jsonObject.addProperty("stamp", ParamsUtil.INSTANCE.getStamp());
            jsonObject.addProperty("userId", ParamsUtil.INSTANCE.getUserId());
            jsonObject.addProperty("token", token);
    
    
    
            requestBody =RequestBody.create(MediaType.parse("application/json"),GsonUtils.toJson(jsonObject));
            
         }
    
             // 添加公共参数Header
             Request newRequest = builder
                    .url(authorizedUrlBuilder.build().toString())
                    .addHeader("Token", token)
                    .addHeader("random", random)
                    .addHeader("time", time)
                    .addHeader("sign", sign)
                    .addHeader("Content-Type", "application/json")
                    .post(requestBody)
                    .build();
    
       return chain.proceed(newRequest);
    }
  2. GET 方式添加 Parameter, 也就是在 URL 的后面拼接参数

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
    
        String path = oldRequest.url().url().toString();
        if (path.contains("user/third-info")) {
    
            TreeMap<String, String> paramsMap = new TreeMap<>();
            paramsMap.put("id", Constant.Id);
            paramsMap.put("UserType", "3");
            paramsMap.put("sn2", DeviceUtil.INSTANCE.getSn());
            paramsMap.put("userToken", AccountManager.INSTANCE.getToken());
            String paramsJson = GsonUtils.toJson(paramsMap);
            Logger.i(TAG, "paramsJson", paramsJson);
    
            TreeMap<String, String> sessionMap = new TreeMap<>();
            sessionMap.put("sid", UUID.randomUUID().toString());
            sessionMap.put("time", time.toString());
            String sessionJson = GsonUtils.toJson(sessionMap);
    
            HttpUrl.Builder builder = oldRequest.url().newBuilder();
            HttpUrl modifiedUrl = builder
                    .addQueryParameter("params", paramsJson)
                    .addQueryParameter("session", sessionJson)
                    .build();
    
            Set<String> parameterNames = modifiedUrl.queryParameterNames();
            ArrayList<String> nameList = new ArrayList<>();
            nameList.addAll(parameterNames);
            TreeMap<String, String> signMap = new TreeMap<>();
            for (int i = 0; i < nameList.size(); i++) {
                signMap.put(nameList.get(i), modifiedUrl.queryParameterValue(i));
            }
    
            modifiedUrl = builder.addQueryParameter("sign", sign(signMap)).build();
    
            Request request = oldRequest.newBuilder().url(modifiedUrl).build();
    
            return chain.proceed(request);
    
        }
    
        return chain.proceed(oldRequest);
    }
  3. 添加公共参数header

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    public Response intercept(Chain chain) throws IOException {
            
        Request request = chain.request();
                request=request.newBuilder()
                        .addHeader("userToken", Token)
                        .addHeader("random", "20201019010309")
                        .addHeader("time", "2020-10-19-01-03-09")
                        .build();
                   
        return chain.proceed(request);
            
    }
  4. From表单添加公共参数

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    public Response intercept(Chain chain) throws IOException {
            
       Request request = chain.request();
                  
                if (request.body() instanceof FormBody) {
                    // 构造新的请求表单
                    FormBody.Builder builder = new FormBody.Builder();
     
                    FormBody body = (FormBody) request.body();
                    // 将原来的参数放入新的表单中
                    for (int i = 0; i < body.size(); i++) {
                        builder.add(body.encodedName(i), body.encodedValue(i));
                    }
                    // 添加公共参数
                    builder.add("sig", ParamsUtil.INSTANCE.getSig());
                    request = request.newBuilder().post(builder.build()).build();//构造新的请求体
                }
     
                return chain.proceed(request);
        }
            
    }