Okhttp中如何在拦截器中的RequestBody添加参数?-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

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

2016-03-11 15:09:57 8994 1

我想在所有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);
            }
        });
取消 提交回答
全部回答(1)
  • 蛮大人123
    2019-07-17 18:59:21

    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);
                }
            });
    0 0
+关注
蛮大人123
我说我不帅他们就打我,还说我虚伪
0
文章
7733
问答
问答排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载