Retrofit網路請求引數註解,@Path、@Query、@Post、Body等總結
阿新 • • 發佈:2018-11-27
Retrofit網路請求引數註解,@Path、@Query、@Post、Body等總結
具體用法參照 Retrofit官網
Retrofit簡介:
- 是一個基於okhttp的網路請求框架
- 通過註解配置網路請求引數
- 圖片連結和圖片上傳
- 支援同步和非同步網路請求
- 支援多種資料的解析,提供對Rxjava的支援
- 可拓展性好,高度封裝,簡潔易用
Retrofit使用介紹:
使用 Retrofit 的步驟共有7個:
- 新增Retrofit庫的依賴
- 建立接收伺服器返回資料的類
- 建立用於描述網路請求的介面
- 建立 Retrofit 例項
- 建立 網路請求介面例項 並 配置網路請求引數
- 傳送網路請求(非同步 / 同步)
- 處理資料
GET - http://192.168.43.173/api/trades
//簡單的get請求(沒有引數)
@GET("trades")
Call<TradesBean> getItem();
//簡單的get請求(URL中帶有引數) @GET("News/{userId}") Call<TradesBean> getItem(@Path("userId") String userId);
//簡單的get請求(URL中帶有兩個引數)
@GET("News/{userId}")
Call<TradesBean> getItem(@Path("userId") String userId,@Path("type") String type);
//引數在url問號之後
@GET("trades")
Call<TradesBean> getItem(@Query("userId") String userId);
@GET("trades")
Call<TradesBean> getItem(@QueryMap Map<String, String> map);
@GET("trades")
Call<TradesBean> getItem(
@Query("userId") String userId,
@QueryMap Map<String, String> map);
POST
//需要補全URL,post的資料只有一條reason
@FormUrlEncoded
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Path("userId") String userId,
@Field("reason") String reason;
//需要補全URL,問號後需要加token,post的資料只有一條reason
@FormUrlEncoded
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Path("userId") String userId,
@Query("token") String token,
@Field("reason") String reason;
//post一個物件
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Path("userId") String userId,
@Query("token") String token,
@Body TradesBean bean;
//用不同註解post一個實體
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Part("entity") TradesBean bean;
PUT
//put一個實體
@PUT("trade/carInfo/{pid}")
Call<TradesBean> putInfo(
@Path("pid") Int pid,
@Body CarInfoBean carInfoBean;)
DELETE
//補全url
@DELETE("trades/{userId}")
Call<TradesBean> deleteInfo(
@Path("userId") String userId;
//補全url並且後面還token
@DELETE("trades/{userId}")
Call<TradesBean> deleteInfo(
@Path("userId") String userId,
@Query("token") String token;)
個人總結
- Path是網址中的引數,例如:trades/{userId}
- Query是問號後面的引數,例如:trades/{userId}?token={token}
- QueryMap 相當於多個@Query
- Field用於Post請求,提交單個數據,然後要加@FormUrlEncoded
- Body相當於多個@Field,以物件的方式提交
- @Streaming:用於下載大檔案
- @Header,@Headers、加請求頭
Tip: 有不好之處請提出寶貴意見 謝謝 !!!