2014-11-02 74 views
8

我想发送一个简单的POST请求与一个实际参数:改造:如何发送带有常量字段的POST请求?

@POST("/token") 
@FormUrlEncoded 
void extendSession(@Field("refresh_token")final String refreshToken); 

但这一要求也应该向服务器请求某个常数的值,如client_idclient_secretgrant_type这是不变的,不应该是一部分的应用程序API。

这样做的最好方法是什么?

回答

8

这是你的方法问题。如果你有常量,你可以为你的调用建立一个默认的地图值。 @FieldMap将适用于构建地图与您的所有必填字段

private void extendSession(String token){ 
    Map params = buildDefaultParams(); 
    params.put("refreshToken", token); 
    getRestAdapter().create(MyApi.class).extendsSession(params); 
} 
private Map buildDefaultParams(){ 
    Map defaults = new HashMap(); 
    defaults.put("client_id", CLIENT_ID); 
    defaults.put("client_secret", CLIENT_SECRET); 
    defaults.put("grant_type", GRANT_TYPE); 
    return defaults; 
} 
    /**then you change your interface to this **/ 
    @POST("/token") 
    @FormUrlEncoded 
    void extendSession(@FieldMap() Map refreshToken); 
+3

这就是我最终做的,虽然它不是一个“优雅”的解决方案。 – 2015-01-01 07:27:01

+1

Github上有一个悬而未决的问题,我也将这个帖子链接到那里。 https://github.com/square/retrofit/issues/951 – 2015-07-28 23:45:17

1

您可以使用Java Method Invocation Builder这一点。

@GenerateMethodInvocationBuilder 
public interface ServiceApi { 
@POST("/token") 
@FormUrlEncoded 
void extendSession(
    @Default("theToken") @Field("refresh_token") final String refreshToken, 
    @Default("theId") @Field("client_id") final String clientId, 
    @Default("theSecret") @Field("client_secret") final String clientSecret, 
    @Default("theType") @Field("grant_type") final String grantType); 
} 

然后你就可以调用,如API:

ServiceApiExtendedSessionBuilder.extendedSession() 
.withRefreshToken("theRefreshToken") 
.invoke(serviceApi); 
0

取而代之的是String,你的界面可以接受一个GrantType对象,它有不同的grant_type工厂方法。这些工厂方法将设置client_id,client_secretgrant_type字段。

@POST("/oauth/token") 
Call<Token> extendSession(@Body GrantType grantType);