Retrofit2 静态编码表单数据?

Retrofit2 Static encoded form data?

我有一个正在处理的新 Android 项目,Retrofit2 对我来说效果很好。但是,在我发送的数据之上,我有一个 url 需要用两个字符串之一命中。

现在看起来像这样:

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

授权类型只是两件事之一,我想把它抽象出来,变成静态的 urls,像这样:

@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);

有没有办法做到这一点?我 2 天的 google-fu 对我没有用,也没有浏览 API 文档和代码。我只是不想在我的代码的各个地方跟踪正确的字符串。

原来答案是 "You can't right now"。

有一个 open issue on Github 功能请求

有另一种方法,一个带有方法示例的 FieldMap 对象,如 this SO post 中所述,但这并不是我想要的,而且只对一个字段进行了矫枉过正。

Retrofit RequestInterceptor 可以完成这项工作吗? 它可以将参数注入到每个请求中...因此您可以从那里编写一个方法,根据您要执行的操作注入正确的参数...

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"  
}