Retrofit2如何在Post、Get、Header上设置固定参数 | 公共参数
原理是使用OkHttp3里面的Interceptor拦截请求。
实例代码如下:
第一步,创建一个OkHttp3拦截器:
public class MyInterceptor implements Interceptor {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newRequestBuilder = request.newBuilder();
//为Header设置公共参数
newRequestBuilder.addHeader("token", "123456");
//为Url设置公共参数
HttpUrl url = request.url().newBuilder().addQueryParameter("token", "123456").build();
newRequestBuilder.url(url);
RequestBody body = request.body();
//为Post表单请求设置公共参数
if (body instanceof FormBody) {
FormBody formBody = (FormBody) body;
FormBody.Builder formBodyBuilder = new FormBody.Builder();
for (int i = 0; i < formBody.size(); i++) {
formBodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
}
//公共参数设置处
formBodyBuilder.add("token", "123456");
newRequestBuilder.post(formBodyBuilder.build());
} else if (body instanceof MultipartBody) {
MultipartBody multipartBody = (MultipartBody) body;
MultipartBody.Builder newMultipartBodyBuilder = new MultipartBody.Builder();
//公共参数设置处
newMultipartBodyBuilder.addPart(Headers.of("Content-Disposition: form-data; name=\"token\""), RequestBody.create("123456", null));
//或者
newMultipartBodyBuilder.addFormDataPart("token", "123456");
for (int i = 0; i < multipartBody.size(); i++) {
MultipartBody.Part part = multipartBody.part(i);
newMultipartBodyBuilder.addPart(part);
}
newRequestBuilder.post(multipartBody);
}
return chain.proceed(newRequestBuilder.build());
}
}
第二步,创建OkHttpClient实例并设置拦截器:
retrofit = new Retrofit.Builder()
.client(new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build())
.baseUrl("http://apis.juhe.cn/").build();