亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

有如下場景:

請求數(shù)據(jù)時:
1. 用戶未登錄時,不帶參數(shù)userId;
2. 登錄時帶上參數(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);

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

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

上面的兩個接口合并為一個:

@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)用的時候傳一個null, 系統(tǒng)也不會出錯,會把這個參數(shù)當(dāng)作沒有。

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

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

當(dāng)然,還可以支持固定參數(shù)與動態(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);

動態(tài)添加Header

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

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

多個Header

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

固定與動態(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)文章

最新評論