Retorfit

1. Retrofit優點

api設計簡潔,註解化配置高度解耦,支持多種解析器,支持Rxjava

2. Retrofit與OKHttp的關係

Retrofit是基於OKHttp的網絡請求框架的二次封裝,其本質仍是OKHttp

3. 與Volley的對比

Volley是基於HttpUrlConnection,Google官方推出只適合輕量級網絡交互如數據傳輸小,不適合大文件上傳下載的場景

4. Retrofit使用

Step1. 依賴包導入
compile ‘com.squareup.refrofit2:retrofit:2.2.0’
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
compile ‘com.squareup.retrofit2:converter-gson:2.0.2’

Step2. 創建接口設置請求類型與參數
新建UserInfoModel(實體對象類)和UserMgrService接口
@GET(“login”)
public Call login(@Query(“username”)String username, @Query(“pwd”)String pwd);
常用參數註解
@GET,@POST : 確定請求方式
@Path : 請求URL的字符替代
@Query : 要傳遞的參數 (@GET請求使用@Query與@QueryMap)
@QueryMap : 包括多個@Query註解參數
@Body : 添加實體類對象
@FormUrlEncoded : URL編碼(@POST請求要加@FormUrlEncoded)
@Field : 要傳遞的參數(@POST請求使用@Field與@FieldMap)
@FieldMap : 包括多個@Field參數

step3. 創建Retrofit對象,設置數據解析器
Retrofit retrofit=new Retrofit.Builder().baseUrl(Constants.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
GsonConverterFactory //gson數據解析器
常用數據解析器
Gson com.squareup.retrofit2:converter-gson:2.0.2
Jackson com.squareup.retrofit2:converter-jackson:2.0.2
Simple XML com.squareup.retrofit2:converter-simplexml:2.0.2
Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2
Moshi com.squareup.retrofit2:converter-moshi:2.0.2
Wire com.squareup.retrofit2:converter-wire:2.0.2
Scalars com.squareup.retrofit2:converter-scalars:2.0.2

step4. 生成接口對象
UserMgrService service=retrofit.create(UserMgrService.class); //動態代理設計模式

step5. 調用接口方法返回Call對象
Call call=service.login(“yonghuming”,”123456”);

step6. 發送請求(同步,異步)
同步:調用Call對象的execute(),返回結果的響應體
異步:調用Call對象的enqueue(),參數是一個回調

Step7. 處理返回結果
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

5. 總結

Retrofit 是基於Okhttp網絡庫的高級封裝
採用註解,網絡請求參數配置更靈活,擴展性更好
RESTful風格的API優先使用Retrofit

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章