欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Retrofit 動(dòng)態(tài)參數(shù)(非固定參數(shù)、非必須參數(shù))(Get、Post請求)

 更新時(shí)間:2018年04月02日 10:21:03   作者:一葉飄舟  
這篇文章主要介紹了詳解Retrofit 動(dòng)態(tài)參數(shù)(非固定參數(shù)、非必須參數(shù))(Get、Post請求),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

詳解Retrofit 動(dòng)態(tài)參數(shù)(非固定參數(shù)、非必須參數(shù))(Get、Post請求)

關(guān)鍵詞:Retrofit 動(dòng)態(tài)參數(shù)、非固定參數(shù)、非必須參數(shù)

有如下場景:

請求數(shù)據(jù)時(shí):
1. 用戶未登錄時(shí),不帶參數(shù)userId;
2. 登錄時(shí)帶上參數(shù)userId.

如下接口:

@GET("index.php?r=default/homepage")
Observable<Response<Exercise>> getDataList(@Query("page") int page);

@GET("index.php?r=default/homepage")
Observable<Response<Exercise>> getDataList(@Query("page") int page, @Query("user_id") int userId);

兩個(gè)接口,區(qū)別就在于有沒有『user_id』參數(shù)。

這樣做,總感覺有點(diǎn)羅嗦,體現(xiàn)不出Retrofit的優(yōu)越性。有沒有更好的方法呢?當(dāng)然有,那就是動(dòng)態(tài)參數(shù)(其實(shí)很簡單)。

上面的兩個(gè)接口合并為一個(gè):

@GET("index.php?r=default/homepage")
Observable<Response<Exercise>> getDataList(@Query("page") int page,@Query("user_id") Integer userId);

使用

登錄:

APIWrapper.getInstance().getDataList(mCurrentPage, 10);

未登錄:

APIWrapper.getInstance().getDataList(mCurrentPage, null);

Retrofit運(yùn)行null值參數(shù),如果在實(shí)際調(diào)用的時(shí)候傳一個(gè)null, 系統(tǒng)也不會(huì)出錯(cuò),會(huì)把這個(gè)參數(shù)當(dāng)作沒有。

對于參數(shù)名稱不固定的情況也可以使用Map

@GET("applist/apps/detail")
Call<ResponsePojo> getDetail(@QueryMap Map<String, String> param);

當(dāng)然,還可以支持固定參數(shù)與動(dòng)態(tài)參數(shù)的混用

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Query("appid") String appid);

修改Header

固定添加Header

@Headers("Accept-Encoding: application/json")

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Query("appid") String appid);

動(dòng)態(tài)添加Header

@Headers("Accept-Encoding: application/json")

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Accept-Encoding") String appid);

多個(gè)Header

@Headers({
  "X-Foo: Bar",
  "X-Ping: Pong"
 })
@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Accept-Encoding") String appid);

固定與動(dòng)態(tài)的Header的混合

@Headers("Accept-Encoding: application/json")

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Location") String appid);

以上用法同樣適用于Post請求。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論