详解Retrofit 动态参数(非固定参数、非必须参数)(Get、Post请求)
详解Retrofit动态参数(非固定参数、非必须参数)(Get、Post请求)
关键词:Retrofit动态参数、非固定参数、非必须参数
有如下场景:
请求数据时:
1.用户未登录时,不带参数userId;
2.登录时带上参数userId.
如下接口:
@GET("index.php?r=default/homepage") Observable>getDataList(@Query("page")intpage); @GET("index.php?r=default/homepage") Observable >getDataList(@Query("page")intpage,@Query("user_id")intuserId);
两个接口,区别就在于有没有『user_id』参数。
这样做,总感觉有点罗嗦,体现不出Retrofit的优越性。有没有更好的方法呢?当然有,那就是动态参数(其实很简单)。
上面的两个接口合并为一个:
@GET("index.php?r=default/homepage") Observable>getDataList(@Query("page")intpage,@Query("user_id")IntegeruserId);
使用
登录:
APIWrapper.getInstance().getDataList(mCurrentPage,10);
未登录:
APIWrapper.getInstance().getDataList(mCurrentPage,null);
Retrofit运行null值参数,如果在实际调用的时候传一个null,系统也不会出错,会把这个参数当作没有。
对于参数名称不固定的情况也可以使用Map
@GET("applist/apps/detail") CallgetDetail(@QueryMapMap param);
当然,还可以支持固定参数与动态参数的混用
@GET("applist/apps/detail?type=detail") CallgetDetail(@Query("appid")Stringappid);
修改Header
固定添加Header
@Headers("Accept-Encoding:application/json") @GET("applist/apps/detail?type=detail") CallgetDetail(@Query("appid")Stringappid);
动态添加Header
@Headers("Accept-Encoding:application/json") @GET("applist/apps/detail?type=detail") CallgetDetail(@Header("Accept-Encoding")Stringappid);
多个Header
@Headers({ "X-Foo:Bar", "X-Ping:Pong" }) @GET("applist/apps/detail?type=detail") CallgetDetail(@Header("Accept-Encoding")Stringappid);
固定与动态的Header的混合
@Headers("Accept-Encoding:application/json") @GET("applist/apps/detail?type=detail") CallgetDetail(@Header("Location")Stringappid);
以上用法同样适用于Post请求。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。