Is there a way to add query parameter to every request with Retrofit 2?
now the Retrofit has release 2.0.0 and this is my solution:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
String uid = "0";
long timestamp = (int) (Calendar.getInstance().getTimeInMillis() / 1000);
String signature = MD5Util.crypt(timestamp + "" + uid + MD5_SIGN);
String base64encode = signature + ":" + timestamp + ":" + uid;
base64encode = Base64.encodeToString(base64encode.getBytes(), Base64.NO_WRAP | Base64.URL_SAFE);
Request request = chain.request();
HttpUrl url = request.url()
.newBuilder()
.addQueryParameter("pageSize", "2")
.addQueryParameter("method", "getAliasList")
.build();
request = request
.newBuilder()
.addHeader("Authorization", "zui " + base64encode)
.addHeader("from_client", "ZuiDeer")
.url(url)
.build();
Response response = chain.proceed(request);
return response;
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiConstants.API_BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
mRestfulService = retrofit.create(RestfulService.class);
For the sake of completeness, here is the full code you need to add a parameter to every Retrofit 2.x request using a OkHttp-Interceptor:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url().newBuilder().addQueryParameter("name","value").build();
request = request.newBuilder().url(url).build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("...")
.client(client)
.build();