Retrofit2 + Okhttp3 request to add a unified body

Foreword

Part talked about Retrofit2 + Okhttp3 Add unity 请求头, this unity is added 请求体, the principle is the same, the parameters are 请求体added to the way 拦截器in, then assigned okhttp.


Code

  • Create a blocker, and add parameters
public class HeaderInterceptor implements Interceptor {

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request original = chain.request();

        //添加请求体参数
        HttpUrl url = original.url().newBuilder()
                .addQueryParameter("name", "value")
                .addQueryParameter("自定义key", "自定义value")
                .build();

        //重新配置请求并返回
        Request request = original.newBuilder()
                .method(original.method(), original.body())
                .url(url)
                .build();

        return chain.proceed(request);
    }

}
  • Configuring interceptors to OkHttp
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                ...
                .addInterceptor(new HeaderInterceptor())
                ...
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

Published 246 original articles · won praise 441 · views 680 000 +

Guess you like

Origin blog.csdn.net/yechaoa/article/details/103178149