Android Retrofit OkHttp添加Interceptor拦截器设置POST请求公共参数 发表于 2019-07-06 | 阅读次数: | 本文字数: 1.8k | 阅读时长 ≈ 2 分钟 12345678910111213141516171819202122232425262728293031323334353637private 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();}