Alireza Alireza - 5 months ago 27
Android Question

Retrofit - Append text to the end of end point after queries inserted

I want to produce the end point like

/api/method?page=1.json
but the problem is queries will be inserted at the end just like
/api/method.json?page=1
.

// from my service
@GET("method.json")
Call<Void> method(@Query("page") int page);

// building retrofit
new Retrofit.Builder()
.baseUrl(URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();


Update/ Following works but I @Blackbelt answer is the best one.

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BASIC : HttpLoggingInterceptor.Level.NONE);
return new OkHttpClient.Builder()
.addInterceptor(logging)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder().url(request.url().toString().concat(".json")).build();
return chain.proceed(request);
}
})
.build();

Answer

I want to produce the end point like /api/method?page=1.json

why. Without the .json it looks better and you somehow hide the information that the response is a json object.

but the problem is queries will be inserted at the end just like /api/method.json?page=1.

That's the expected behaviour. As you saw it appends what you are providing as parameter. So you could change from

Call<Void> method(@Query("page") int page);

to

Call<Void> method(@Query("page") String page);

and then you call it like

method(String.valueOf(page).concat(".json"));
Comments