Retrofit 2.0 使用教程
本文轉載自:http://blog.csdn.net/carson_ho/article/details/73732076
前言
- 在
Andrroid
開發中,網路請求十分常用 - 而在
Android
網路請求庫中,Retrofit
是當下最熱的一個網路請求庫
- 今天,我將獻上一份非常詳細
Retrofit v2.0
的使用教程,希望你們會喜歡。
目錄
1. 簡介
特別注意:
- 準確來說,Retrofit 是一個 RESTful 的 HTTP 網路請求框架的封裝。
- 原因:網路請求的工作本質上是
OkHttp
完成,而 Retrofit 僅負責 網路請求介面的封裝
- App應用程式通過 Retrofit 請求網路,實際上是使用 Retrofit 介面層封裝請求引數、Header、Url 等資訊,之後由 OkHttp 完成後續的請求操作
- 在服務端返回資料之後,OkHttp 將原始的結果交給 Retrofit,Retrofit根據使用者的需求對結果進行解析
2. 與其他開源請求庫對比
除了Retrofit,如今Android中主流的網路請求框架有:
- Android-Async-Http
- Volley
- OkHttp
下面是簡單介紹:
一圖讓你瞭解全部的網路請求庫和他們之間的區別!
附:各個主流網路請求庫的Github地址
3. 使用介紹
使用 Retrofit 的步驟共有7個:
步驟1:新增Retrofit庫的依賴
步驟2:建立 接收伺服器返回資料 的類
步驟3:建立 用於描述網路請求 的介面
步驟4:建立 Retrofit 例項
步驟5:建立 網路請求介面例項 並 配置網路請求引數
步驟6:傳送網路請求(非同步 / 同步)
封裝了 資料轉換、執行緒切換的操作
步驟7: 處理伺服器返回的資料
接下來,我們一步步進行講解。
步驟1:新增Retrofit庫的依賴
1. 在 Gradle
加入Retrofit
庫的依賴
由於
Retrofit
是基於OkHttp
,所以還需要新增OkHttp
庫依賴
build.gradle
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
2. 新增 網路許可權
AndroidManifest.xml
- 1
- 1
步驟2:建立 接收伺服器返回資料 的類
Reception.Java
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
步驟3:建立 用於描述網路請求 的介面
- Retrofit將 Http請求 抽象成 Java介面:採用 註解 描述網路請求引數 和配置網路請求引數
- 用 動態代理 動態 將該介面的註解“翻譯”成一個 Http 請求,最後再執行 Http 請求
- 注:介面中的每個方法的引數都需要使用註解標註,否則會報錯
- 用 動態代理 動態 將該介面的註解“翻譯”成一個 Http 請求,最後再執行 Http 請求
GetRequest_Interface.interface
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
註解型別
註解說明
第一類:網路請求方法
詳細說明:
a. @GET、@POST、@PUT、@DELETE、@HEAD
以上方法分別對應 HTTP中的網路請求方式
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 網路請求的完整 Url =在建立Retrofit例項時通過.baseUrl()設定 +網路請求介面的註解設定(下面稱 “path“ )
- 具體整合的規則如下:
建議採用第三種方式來配置,並儘量使用同一種路徑形式。
b. @HTTP
- 作用:替換@GET、@POST、@PUT、@DELETE、@HEAD註解的作用 及 更多功能拓展
- 具體使用:通過屬性method、path、hasBody進行設定
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
第二類:標記
a. @FormUrlEncoded
- 作用:表示傳送form-encoded的資料
每個鍵值對需要用@Filed來註解鍵名,隨後的物件需要提供值。
b. @Multipart
- 作用:表示傳送form-encoded的資料(適用於 有檔案 上傳的場景)
每個鍵值對需要用@Part來註解鍵名,隨後的物件需要提供值。
具體使用如下:
GetRequest_Interface
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
第三類:網路請求引數
詳細說明
a. @Header & @Headers
- 作用:新增請求頭 &新增不固定的請求頭
- 具體使用如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
b. @Body
- 作用:以
Post
方式 傳遞 自定義資料型別 給伺服器 - 特別注意:如果提交的是一個Map,那麼作用相當於
@Field
不過Map要經過
FormBody.Builder
類處理成為符合 Okhttp 格式的表單,如:
- 1
- 2
- 3
- 1
- 2
- 3
c. @Field & @FieldMap
- 作用:傳送 Post請求 時提交請求的表單欄位
- 具體使用:與
@FormUrlEncoded
註解配合使用
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28