Android Retrofit OkHttp添加Interceptor拦截器设置POST请求公共参数

private HttpServiceImpl() {
    OkHttpClient httpClient = new OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            // 对请求进行拦截处理,添加统一的请求头及打印请求报文和返回报文
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if ("POST".equals(request.method())) {
                        if (request.body() instanceof FormBody) {
                            FormBody.Builder bodyBuilder = new FormBody.Builder();
                            FormBody formBody = (FormBody) request.body();
                            // 先复制原来的参数
                            for (int i = 0; i < formBody.size(); i++) {
                                bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                            }
                            // 添加公共参数
                            formBody = bodyBuilder
                                    .addEncoded("version", "1.0.0")
                                    .addEncoded("appkey", "yeyuanxinyi")
                                    .addEncoded("timestamp", String.valueOf(System.currentTimeMillis()))
                                    .build();

                            request = request.newBuilder().post(formBody).build();
                        }
                    }
                    return chain.proceed(request);
                }
            })
            .build();
    return new Retrofit.Builder()
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(getBaseUrl())
            .build();
}

 

你可能感兴趣的:(android)