Retrofit 動態引數(非固定引數、非必須引數)(Get、Post請求)
阿新 • • 發佈:2019-01-07
關鍵詞: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請求。
That’s all.
或許你對這個也感興趣: