5

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

现在它看起来像这样:

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

授权类型只是两件事之一,我想将其抽象为静态网址,如下所示:

@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 文档和代码。我只是不想在我的代码的各个地方跟踪正确的字符串。

4

2 回答 2

0

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"  
}
于 2016-02-07T21:12:23.523 回答
0

原来答案是“你现在不能”。

Github 上有一个关于功能请求的未解决问题

有一种替代方法,一个带有方法示例的 FieldMap 对象,如这篇 SO 帖子中提到的,但这并不是我想要的,而且对于一个字段来说太过分了。

于 2016-02-03T15:03:21.897 回答