Retrofit: How to send a POST request with constant fields?

后端 未结 4 1298
旧时难觅i
旧时难觅i 2021-02-19 09:29

I want to sent a simple POST request with one actual parameter:

@POST(\"/token\")
@FormUrlEncoded
void extendSession(@Field(\"refresh_token\")final String refres         


        
相关标签:
4条回答
  • 2021-02-19 10:19

    You may use Java Method Invocation Builder for this.

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

    And then you can invoke the api like:

    ServiceApiExtendedSessionBuilder.extendedSession()
     .withRefreshToken("theRefreshToken")
     .invoke(serviceApi);
    
    0 讨论(0)
  • 2021-02-19 10:19

    Instead of a String, your interface could accept a GrantType object which has factory methods for different grant_types. These factory methods would set the client_id, client_secret, and grant_type fields.

    @POST("/oauth/token")
    Call<Token> extendSession(@Body GrantType grantType);
    
    0 讨论(0)
  • 2021-02-19 10:26

    It is matter of your approach. If you have the constants you can build a default Map of values required for your call. @FieldMap will be suitable for building a Map with all your required fields

    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);
    
    0 讨论(0)
  • 2021-02-19 10:32

    A bit of an old question but after thinking about this myself for a while, this is what I came up with. I would love to hear any thoughts!

    As is standard, I have my @POST defined in an interface called AuthWebservice:

    interface AuthWebservice {
    
        @POST("oauth/token")
        @FormUrlEncoded
        fun refreshToken(
            @Field("grant_type")
            grantType: GrantType,
    
            @Field("client_id")
            clientId: String,
    
            @Field("client_secret")
            clientSecret: String,
    
            @Field("refresh_token")
            refreshToken: String
        ): Call<AccessToken>
    
    }
    

    [NOTE: I'm using Dagger for dependency injection but the following logic would work no matter where you instantiate your webservice]

    In my NetworkModule I have the following to get an instance of AuthWebservice:

    @Module
    class NetworkModule {
        ...
    
        @Provides
        @Singleton
        fun providesAuthWebservice(
            retrofit: Retrofit
        ): AuthWebservice = retrofit.create(AuthWebservice::class.java)
    
        ...
    }
    

    So here's my solution: I also include the following method definition inside AuthWebservice:

    fun refreshToken(refreshToken: String): Call<AccessToken>
    

    Note there are no annotations of any sort, and the method returns the same data type as the version that includes all of the arguments. This will compile, but obviously it will fail at runtime if you try to call it, something akin to the following:

    java.lang.IllegalArgumentException: HTTP method annotation is required (e.g., @GET, @POST, etc.). for method AuthWebservice.refreshToken

    Now I make a class called AuthWebserviceWrapper that takes an instance of AuthWebservice. In most cases it just calls the corresponding method on the base instance, except for the method I just added above:

    class AuthWebserviceWrapper(private val base: AuthWebservice) : AuthWebservice {
    
        // Just call the base method.
        override fun refreshToken(
            grantType: GrantType,
            clientId: String,
            clientSecret: String,
            refreshToken: String
        ): Call<AccessToken> = base.refreshToken(
            grantType, 
            clientId,
            clientSecret, 
            refreshToken)
    
        // Call the base method with defaults!
        override fun refreshToken(refreshToken: String): Call<AccessToken> = 
            base.refreshToken(
                GrantType.REFRESH_TOKEN, // Default value 
                BuildConfig.MY_CLIENT_ID, // Default value 
                BuildConfig.MY_CLIENT_SECRET,  // Default value
                refreshToken
            )
    
    }
    

    And finally, back in NetworkModule, I wrap Retrofit's default implementation like so:

    @Module
    class NetworkModule {
        ...
    
        @Provides
        @Singleton
        fun providesAuthWebservice(
            retrofit: Retrofit
        ): AuthWebservice = AuthWebserviceWrapper(retrofit.create(AuthWebservice::class.java))
    
        ...
    }
    

    Now when I call refreshToken I get my method with default values:

    class MyClass @Inject constructor(authWebservice: AuthWebservice) {
    
        fun doSomething(refreshToken: String) {
           val call = authWebservice.refreshToken(refreshToken)
        }
    
    }
    

    This does of course introduce some boilerplate, of which I am not a fan, but I think ultimately it's the cleanest way of making a webservice call without introducing the need for @Body or @FieldMap.

    Anyway, that's my story and I'm sticking to it.

    0 讨论(0)
提交回复
热议问题