I would like to always add a parameter to my Retrofit calls. For values that I can hard code I can simply use
@POST("/myApi?myParam=myValue")
but what if I want to append android.os.Build.MODEL
?
@POST("/myApi?machineName="+ Build.MODEL)
doesn't work. It would be useful to be able to abstract this part of the network call away from the implementing code.
EDIT
I can add Build.MODEL
to all of my api calls by using a RequestInterceptor
. However it still eludes me how to add it selectively to only some of my api calls while still using the same RestAdapter
.
EDIT 2
Fixed the title which was all sorts of wrong.
EDIT 3
Current implementation:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("myapi")
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestInterceptor.RequestFacade request) {
request.addQueryParam("machineName", Build.MODEL);
}
})
.build();
API_SERVICE = restAdapter.create(ApiService.class);
Build.MODEL
is not available for use in an annotation because it cannot be resolved at compile time. It's only available at runtime (because it loads from a property).
There are two ways to accomplish this. The first is using a RequestInterceptor
which you mention in the question.
The second is using a @Query
parameter on the method.
@POST("/myApi")
Response doSomething(@Query("machineName") String machineName);
This requires you to pass Build.MODEL
when invoking the API. If you want, you can wrap the Retrofit interface in an API that's more friendly to the application layer that does this for you.
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