Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit: add runtime parameter to interface?

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);
like image 849
GDanger Avatar asked Sep 03 '14 20:09

GDanger


1 Answers

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.

like image 104
Jake Wharton Avatar answered Oct 05 '22 17:10

Jake Wharton