您好,登錄后才能下訂單哦!
詳解Retrofit 動(dòng)態(tài)參數(shù)(非固定參數(shù)、非必須參數(shù))(Get、Post請(qǐng)求)
關(guān)鍵詞:Retrofit 動(dòng)態(tài)參數(shù)、非固定參數(shù)、非必須參數(shù)
有如下場(chǎng)景:
請(qǐng)求數(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ū)別就在于有沒(méi)有『user_id』參數(shù)。
這樣做,總感覺(jué)有點(diǎn)羅嗦,體現(xiàn)不出Retrofit的優(yōu)越性。有沒(méi)有更好的方法呢?當(dāng)然有,那就是動(dòng)態(tài)參數(shù)(其實(shí)很簡(jiǎn)單)。
上面的兩個(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)作沒(méi)有。
對(duì)于參數(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請(qǐng)求。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。