5

I have a new Android project I am working on, and Retrofit2 is working well for me. However, I have one url that I need to hit, with one of two strings, on top of the data I send.

Right now it looks like this:

@FormUrlEncoded
@POST("token")
Call<AccessResponse> requestAccess(@Field("grant_type") String type, @Field("code") String authCode, @Field("client_id") String ApiKey);

the grant type is only one of two things, and I would like to abstract it away, into static urls, like this:

@FormUrlEncoded
@POST("token")
@Field("grant_type","type1")
Call<AccessResponse> requestAccess( @Field("code") String authCode, @Field("client_id") String ApiKey);

@FormUrlEncoded
@POST("token")
@Field("grant_type","type2")
Call<AccessResponse> refreshAccess( @Field("code") String authCode, @Field("client_id") String ApiKey);

Is there a way to accomplish this? my 2 days of google-fu haven't worked for me, nor has browsing the API docs and code. I just don't want to have to keep track of the correct string in the various places in my code.

mix3d
  • 4,122
  • 2
  • 25
  • 47

2 Answers2

0

Turns out the answer is "You can't right now".

There is an open issue on Github for the feature request

There is an alternative approach, a FieldMap object with a method example as mentioned in this SO post, but it is not exactly what I was looking for, and overkill for just one field.

Community
  • 1
  • 1
mix3d
  • 4,122
  • 2
  • 25
  • 47
0

Could the Retrofit RequestInterceptor do the job ? It can inject parameters into each request... so from there you could maybe write a method that injects the right parameter depending on what you're trying to do...

RequestInterceptor requestInterceptor = new RequestInterceptor() {
       @Override
       public void intercept(RequestFacade request) {
           request.addQueryParam("grant_type", getGrantType());
       }
};
private String getGrantType()
{
     // do your stuff and :   
    return "type1"; // or "type2"  
}
JBA
  • 2,889
  • 1
  • 21
  • 38
  • If I was doing query params this could work, but what about adding to form data? – mix3d Feb 08 '16 at 21:38
  • Query params can be added directly via the @GET definition, according to their docs, like `@GET("users/list?param=static"), but this still doesn't help the goal of form data. Like the feature request states on github, there isn't an easy way to do this yet. – mix3d Feb 08 '16 at 22:10