I need to add a query parameter to every request made by Retrofit 2.0.0-beta2 library. I found this solution for Retrofit 1.9, but how to add RequestInterceptor
in newest library version?
My interface:
@GET("user/{id}") Call<User> getUser(@Path("id")long id); @GET("users/") Call<List<User>> getUser();
Client:
Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(CLIENT) // custom OkHTTP Client .build(); service = retrofit.create(userService.class);
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
POST should not have query param. You can implement the service to honor the query param, but this is against REST spec.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With