Retrofit 動態參數(非固定參數、非必須參數)(Get、Post請求)

關鍵詞:Retrofit 動態參數、非固定參數、非必須參數

有如下場景:

請求數據時: 
1. 用戶未登錄時,不帶參數userId; 
2. 登錄時帶上參數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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

兩個接口,區別就在於有沒有『user_id』參數。

這樣做,總感覺有點羅嗦,體現不出Retrofit的優越性。有沒有更好的方法呢?當然有,那就是動態參數(其實很簡單)。

上面的兩個接口合併爲一個:

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

使用

登錄:

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

未登錄:

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

Retrofit運行null值參數,如果在實際調用的時候傳一個null, 系統也不會出錯,會把這個參數當作沒有。

對於參數名稱不固定的情況也可以使用Map

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

當然,還可以支持固定參數與動態參數的混用

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

修改Header

固定添加Header

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

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

動態添加Header

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

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

多個Header

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

固定與動態的Header的混合

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

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

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

That’s all.

或許你對這個也感興趣:

Retrofit2.0 公共參數(固定參數)

發佈了65 篇原創文章 · 獲贊 26 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章