Okhttp中如何在拦截器中的RequestBody添加参数?
澳门美高梅官网
澳门美高梅官网
当前位置 : 澳门美高梅官网 > 美高梅娱乐

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

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

httpClient.addInterceptornew Interceptor {
            @Override
            public Response interceptChain 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
                        .methodoriginal.method,original.body;

                Request request = requestBuilder.build;
                return chain.proceedrequest;
            }
        };

求帮助,谢了。

  1. 可以遍历formBody,循环添加 formBody

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

OkHttpClient.Builder httpClient = new OkHttpClient.Builder
httpClient.addInterceptornew Interceptor {
            @Override
            public Response interceptChain chain throws IOException {
                Request original = chain.request;

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

                //请求体定制:统一添加token参数
                iforiginal.body instanceof FormBody{
                    FormBody.Builder newFormBody = new FormBody.Builder;
                    FormBody oidFormBody = FormBody original.body;
                    for int i = 0;i<oidFormBody.size;i++{
                        newFormBody.addEncodedoidFormBody.encodedNamei,oidFormBody.encodedValuei;
                    }
                    newFormBody.add"token",Constant.API_TOKEN;
                    requestBuilder.methodoriginal.method,newFormBody.build;
                }

                Request request = requestBuilder.build;
                return chain.proceedrequest;
            }
        };

栏目列表

广告位

澳门美高梅官网