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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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();
}

Click and drag to move