詳解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);
兩個接口,區別就在于有沒有『user_id』參數。
這樣做,總感覺有點羅嗦,體現不出Retrofit的優越性。有沒有更好的方法呢?當然有,那就是動態參數(其實很簡單)。
上面的兩個接口合并為一個:
@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運行null值參數,如果在實際調用的時候傳一個null, 系統也不會出錯,會把這個參數當作沒有。
對于參數名稱不固定的情況也可以使用Map
@GET("applist/apps/detail")
Call<ResponsePojo> getDetail(@QueryMap Map<String, String> param);
當然,還可以支持固定參數與動態參數的混用
@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);
動態添加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);
固定與動態的Header的混合
@Headers("Accept-Encoding: application/json")
@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Location") String appid);
以上用法同樣適用于Post請求。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。