Retrofit 2:@FormUrlEncoded with default fields

时间:2015-09-09 06:50:46

标签: java android retrofit

我需要使用application/x-www-form-urlencoded标头发送请求。响应是JSON格式的一些音乐专辑的列表。可以有两个可选参数:总计(默认值= 5)和开始(默认值= 0)

以下是我用来发送此请求的界面:

public interface MusicService {
    @Headers("Accept: Application/JSON")
    @FormUrlEncoded
    @POST("album/featured-albums")
    Call<List<Album>> listFeaturedAlbums(@Field("total") int total, @Field("begin") int begin);
}

问题是,如何将默认值设置为这些字段中的一个或两个,这样我就不必在每个请求中发送参数。例如,我想在每个请求中获得30个项目,只需使用开始字段。或者我想使用两个字段的默认值:

public interface MusicService {
    @Headers("Accept: Application/JSON")
    @FormUrlEncoded
    @POST("album/featured-albums")
    Call<List<Album>> listFeaturedAlbums();
}

有了这个,我收到一个错误:

  

java.lang.IllegalArgumentException:表单编码方法必须至少包含一个@Field。

3 个答案:

答案 0 :(得分:4)

目前我不认为你可以用非hackish的方式做到这一点。

改造中的家伙正致力于添加此功能:Allow specifying default @Field values. #951

完成后,您可以关注此主题。或者帮助他们并提交PR:)

答案 1 :(得分:0)

Call<List<Album>> listFeaturedAlbums(@Body CustomFields );

class CustomFields {
 String total;
 String begin = 0;
 public CustomFields( String total ) {
   this.total = total;
 }
...
getters&setters
..
}

答案 2 :(得分:0)

你必须像这样添加请求头:

 @Headers("Content-Type: application/x-www-form-urlencoded")

它对我有用