Okhttp中如何在拦截器中的RequestBody添加参数?

我想在所有POST请求中统一添加参数Token.(注意,不是添加在header里面)
如代码:我就是想把formBody2,添加在formBody中。

httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();

                FormBody formBody = (FormBody) original.body();

                FormBody formBody2 = new FormBody.Builder().add("token", “123456”).build();

                //请求定制:添加请求头
                Request.Builder requestBuilder = original.newBuilder()
                        .addHeader("APIKEY", Constant.API_KEY)
                        .method(original.method(),original.body());

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

求帮助,谢了。

阅读 24.4k
1 个回答
  1. 可以遍历formBody,循环添加 formBody

  2. 最好的办法是重写 FormBody,追加添加参数的方法。

OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();

                //请求定制:添加请求头
                Request.Builder requestBuilder = original.newBuilder()
                        .header("APIKEY", Constant.API_KEY);

                //请求体定制:统一添加token参数
                if(original.body() instanceof FormBody){
                    FormBody.Builder newFormBody = new FormBody.Builder();
                    FormBody oidFormBody = (FormBody) original.body();
                    for (int i = 0;i<oidFormBody.size();i++){
                        newFormBody.addEncoded(oidFormBody.encodedName(i),oidFormBody.encodedValue(i));
                    }
                    newFormBody.add("token",Constant.API_TOKEN);
                    requestBuilder.method(original.method(),newFormBody.build());
                }

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏