前言
在Andrroid開發中,網絡請求十分常用
而在Android網絡請求庫中,Retrofit是當下最熱的一個網絡請求庫
今天,我將獻上一份非常詳細Retrofit v2.0的使用教程,希望你們會喜歡。
如果對Retrofit v2.0的源碼感興趣,可看文章:Android:手把手帶你深入剖析 Retrofit 2.0 源碼
特別注意:
準確來說,Retrofit 是一個 RESTful 的 HTTP 網絡請求框架的封裝。
原因:網絡請求的工作本質上是?OkHttp?完成,而 Retrofit 僅負責 網絡請求接口的封裝
App應用程序通過 Retrofit 請求網絡,實際上是使用 Retrofit 接口層封裝請求參數、Header、Url 等信息,之后由 OkHttp 完成后續的請求操作
在服務端返回數據之后,OkHttp 將原始的結果交給 Retrofit,Retrofit根據用戶的需求對結果進行解析
除了Retrofit,如今Android中主流的網絡請求框架有:
Android-Async-Http
Volley
OkHttp
下面是簡單介紹:
一圖讓你了解全部的網絡請求庫和他們之間的區別!
附:各個主流網絡請求庫的Github地址
使用 Retrofit 的步驟共有7個:
步驟1:添加Retrofit庫的依賴?
步驟2:創建 接收服務器返回數據 的類?
步驟3:創建 用于描述網絡請求 的接口?
步驟4:創建 Retrofit 實例?
步驟5:創建 網絡請求接口實例 并 配置網絡請求參數?
步驟6:發送網絡請求(異步 / 同步)
封裝了 數據轉換、線程切換的操作
步驟7:?處理服務器返回的數據
接下來,我們一步步進行講解。
1. 在?Gradle加入Retrofit庫的依賴
由于Retrofit是基于OkHttp,所以還需要添加OkHttp庫依賴
build.gradle
dependencies {? ? compile'com.squareup.retrofit2:retrofit:2.0.2'// Retrofit庫compile'com.squareup.okhttp3:okhttp:3.1.2'// Okhttp庫}
1
2
3
4
5
6
2. 添加 網絡權限?
AndroidManifest.xml
1
Reception.java
public class Reception {...// 根據返回數據的格式和數據解析方式(Json、XML等)定義? ? // 下面會在實例進行說明? ? ? ? }
1
2
3
4
5
Retrofit將 Http請求 抽象成 Java接口:采用?注解?描述網絡請求參數 和配置網絡請求參數?
用 動態代理 動態 將該接口的注解“翻譯”成一個 Http 請求,最后再執行 Http 請求?
注:接口中的每個方法的參數都需要使用注解標注,否則會報錯
GetRequest_Interface.interface
publicinterfaceGetRequest_Interface {? ? @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")? ? Call? getCall();// @GET注解的作用:采用Get方法發送網絡請求// getCall() = 接收網絡請求數據的方法// 其中返回類型為Call<*>,*是接收數據的類(即上面定義的Translation類)// 如果想直接獲得Responsebody中的內容,可以定義網絡請求返回值為Call<ResponseBody>}
1
2
3
4
5
6
7
8
9
10
下面詳細介紹Retrofit 網絡請求接口 的注解類型。
第一類:網絡請求方法
詳細說明:?
a. @GET、@POST、@PUT、@DELETE、@HEAD?
以上方法分別對應 HTTP中的網絡請求方式
publicinterfaceGetRequest_Interface {? ? @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")? ? Call? getCall();// @GET注解的作用:采用Get方法發送網絡請求// getCall() = 接收網絡請求數據的方法// 其中返回類型為Call<*>,*是接收數據的類(即上面定義的Translation類)}
1
2
3
4
5
6
7
8
此處特意說明URL的組成:Retrofit把 網絡請求的URL 分成了兩部分設置:
// 第1部分:在網絡請求接口的注解設置@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")Call? getCall();// 第2部分:在創建Retrofit實例時通過.baseUrl()設置Retrofit retrofit =newRetrofit.Builder()? ? ? ? ? ? ? ? .baseUrl("http://fanyi.youdao.com/")//設置網絡請求的Url地址.addConverterFactory(GsonConverterFactory.create())//設置數據解析器.build();// 從上面看出:一個請求的URL可以通過 替換塊 和 請求方法的參數 來進行動態的URL更新。// 替換塊是由 被{}包裹起來的字符串構成// 即:Retrofit支持動態改變網絡請求根目錄
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進行設置
publicinterfaceGetRequest_Interface{/**
? ? * method:網絡請求的方法(區分大小寫)
? ? * path:網絡請求地址路徑
? ? * hasBody:是否有請求體
? ? */@HTTP(method ="GET", path ="blog/{id}", hasBody =false)? ? Call getCall(@Path("id")intid);// {id} 表示是一個變量// method 的值 retrofit 不會做處理,所以要自行保證準確}
1
2
3
4
5
6
7
8
9
10
11
a. @FormUrlEncoded
作用:表示發送form-encoded的數據
每個鍵值對需要用@Filed來注解鍵名,隨后的對象需要提供值。
b. @Multipart
作用:表示發送form-encoded的數據(適用于 有文件 上傳的場景)?
每個鍵值對需要用@Part來注解鍵名,隨后的對象需要提供值。?
具體使用如下:?
GetRequest_Interface
public interface GetRequest_Interface {/**
? ? ? ? *表明是一個表單格式的請求(Content-Type:application/x-www-form-urlencoded)
? ? ? ? * <code>Field("username")</code> 表示將后面的 <code>String name</code> 中name的取值作為 username 的值
? ? ? ? */@POST("/form")@FormUrlEncodedCall testFormUrlEncoded1(@Field("username") String name,@Field("age") int age);/**? ? ? ? * {@linkPart} 后面支持三種類型,{@linkRequestBody}、{@linkokhttp3.MultipartBody.Part} 、任意類型? ? ? ? * 除 {@linkokhttp3.MultipartBody.Part} 以外,其它類型都必須帶上表單字段({@linkokhttp3.MultipartBody.Part} 中已經包含了表單字段的信息),? ? ? ? */@POST("/form")@MultipartCall testFileUpload1(@Part("name") RequestBody name,@Part("age") RequestBody age,@PartMultipartBody.Part file);}// 具體使用GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);// @FormUrlEncoded Call call1 = service.testFormUrlEncoded1("Carson",24);//? @MultipartRequestBody name = RequestBody.create(textType,"Carson");? ? ? ? RequestBody age = RequestBody.create(textType,"24");? ? ? ? MultipartBody.Part filePart = MultipartBody.Part.createFormData("file","test.txt", file);? ? ? ? Call call3 = service.testFileUpload1(name, age, filePart);
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
作用:添加請求頭 &添加不固定的請求頭
具體使用如下:
// @Header@GET("user")Call getUser(@Header("Authorization") String authorization)// @Headers@Headers("Authorization: authorization")@GET("user")Call getUser()// 以上的效果是一致的。// 區別在于使用場景和使用方式// 1. 使用場景:@Header用于添加不固定的請求頭,@Headers用于添加固定的請求頭// 2. 使用方式:@Header作用于方法的參數;@Headers作用于方法
1
2
3
4
5
6
7
8
9
10
11
12
13
b. @Body
作用:以?Post方式 傳遞 自定義數據類型 給服務器
特別注意:如果提交的是一個Map,那么作用相當于?@Field?
不過Map要經過?FormBody.Builder?類處理成為符合 Okhttp 格式的表單,如:
FormBody.Builderbuilder = new FormBody.Builder();builder.add("key","value");
1
2
3
c. @Field & @FieldMap
作用:發送 Post請求 時提交請求的表單字段
具體使用:與?@FormUrlEncoded?注解配合使用
publicinterfaceGetRequest_Interface{/**
? ? ? ? *表明是一個表單格式的請求(Content-Type:application/x-www-form-urlencoded)
? ? ? ? * <code>Field("username")</code> 表示將后面的 <code>String name</code> 中name的取值作為 username 的值
? ? ? ? */@POST("/form")@FormUrlEncodedCall testFormUrlEncoded1(@Field("username") String name,@Field("age")intage);/**
? ? ? ? * Map的key作為表單的鍵
? ? ? ? */@POST("/form")@FormUrlEncodedCall testFormUrlEncoded2(@FieldMapMap map);}// 具體使用// @FieldCall call1 = service.testFormUrlEncoded1("Carson",24);// @FieldMap// 實現的效果與上面相同,但要傳入MapMap map =newHashMap<>();? ? ? ? map.put("username","Carson");? ? ? ? map.put("age",24);? ? ? ? Call call2 = service.testFormUrlEncoded2(map);
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
d. @Part & @PartMap
作用:發送 Post請求 時提交請求的表單字段
與@Field的區別:功能相同,但攜帶的參數類型更加豐富,包括數據流,所以適用于 有文件上傳 的場景
具體使用:與?@Multipart?注解配合使用
public interface GetRequest_Interface {/**? ? ? ? * {@linkPart} 后面支持三種類型,{@linkRequestBody}、{@linkokhttp3.MultipartBody.Part} 、任意類型? ? ? ? * 除 {@linkokhttp3.MultipartBody.Part} 以外,其它類型都必須帶上表單字段({@linkokhttp3.MultipartBody.Part} 中已經包含了表單字段的信息),? ? ? ? */@POST("/form")@MultipartCall testFileUpload1(@Part("name") RequestBody name,@Part("age") RequestBody age,@PartMultipartBody.Part file);/**? ? ? ? * PartMap 注解支持一個Map作為參數,支持 {@linkRequestBody } 類型,? ? ? ? * 如果有其它的類型,會被{@linkretrofit2.Converter}轉換,如后面會介紹的 使用{@linkcom.google.gson.Gson} 的 {@linkretrofit2.converter.gson.GsonRequestBodyConverter}? ? ? ? * 所以{@linkMultipartBody.Part} 就不適用了,所以文件只能用@PartMultipartBody.Part ? ? ? ? */@POST("/form")@MultipartCall testFileUpload2(@PartMapMap args,@PartMultipartBody.Part file);@POST("/form")@MultipartCall testFileUpload3(@PartMapMap args);}// 具體使用MediaType textType = MediaType.parse("text/plain");? ? ? ? RequestBody name = RequestBody.create(textType,"Carson");? ? ? ? RequestBody age = RequestBody.create(textType,"24");? ? ? ? RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"),"這里是模擬文件的內容");// @PartMultipartBody.Part filePart = MultipartBody.Part.createFormData("file","test.txt", file);? ? ? ? Call call3 = service.testFileUpload1(name, age, filePart);? ? ? ? ResponseBodyPrinter.printResponseBody(call3);// @PartMap// 實現和上面同樣的效果Map fileUpload2Args =newHashMap<>();? ? ? ? fileUpload2Args.put("name", name);? ? ? ? fileUpload2Args.put("age", age);//這里并不會被當成文件,因為沒有文件名(包含在Content-Disposition請求頭中),但上面的 filePart 有//fileUpload2Args.put("file", file);Call call4 = service.testFileUpload2(fileUpload2Args, filePart);//單獨處理文件ResponseBodyPrinter.printResponseBody(call4);}
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
e. @Query和@QueryMap
作用:用于?@GET?方法的查詢參數(Query = Url 中 ‘?’ 后面的 key-value)
如:url =?http://www.println.net/?cate=android,其中,Query = cate
具體使用:配置時只需要在接口方法中增加一個參數即可:
@GET("/")? ? ? Call cate(@Query("cate") String cate);}// 其使用方式同@Field與@FieldMap,這里不作過多描述
1
2
3
4
5
6
f. @Path
作用:URL地址的缺省值
具體使用:
publicinterfaceGetRequest_Interface{@GET("users/{user}/repos")? ? ? ? Call? getBlog(@Path("user") String user );// 訪問的API是:https://api.github.com/users/{user}/repos// 在發起請求時, {user} 會被替換為方法的第一個參數 user(被@Path注解作用)}
1
2
3
4
5
6
7
g. @Url
作用:直接傳入一個請求的 URL變量 用于URL設置
具體使用:
publicinterfaceGetRequest_Interface{@GETCall testUrlAndQuery(@UrlString url,@Query("showAll")booleanshowAll);// 當有URL注解時,@GET傳入的URL就可以省略// 當GET、POST...HTTP等方法中沒有設置Url時,則必須使用 {@link Url}提供}
1
2
3
4
5
6
7
8
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://fanyi.youdao.com/") // 設置網絡請求的Url地址.addConverterFactory(GsonConverterFactory.create()) // 設置數據解析器.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺.build();
1
2
3
4
5
Retrofit支持多種數據解析方式
使用時需要在Gradle添加依賴
數據解析器Gradle依賴
Gsoncom.squareup.retrofit2:converter-gson:2.0.2
Jacksoncom.squareup.retrofit2:converter-jackson:2.0.2
Simple XMLcom.squareup.retrofit2:converter-simplexml:2.0.2
Protobufcom.squareup.retrofit2:converter-protobuf:2.0.2
Moshicom.squareup.retrofit2:converter-moshi:2.0.2
Wirecom.squareup.retrofit2:converter-wire:2.0.2
Scalarscom.squareup.retrofit2:converter-scalars:2.0.2
Retrofit支持多種網絡請求適配器方式:guava、Java8和rxjava?
使用時如使用的是?Android?默認的?CallAdapter,則不需要添加網絡請求適配器的依賴,否則則需要按照需求進行添加?
Retrofit 提供的?CallAdapter
使用時需要在Gradle添加依賴:
網絡請求適配器Gradle依賴
guavacom.squareup.retrofit2:adapter-guava:2.0.2
Java8com.squareup.retrofit2:adapter-java8:2.0.2
rxjavacom.squareup.retrofit2:adapter-rxjava:2.0.2
// 創建 網絡請求接口 的實例? ? ? ? GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);//對 發送請求 進行封裝Callcall= request.getCall();
1
2
3
4
5
封裝了 數據轉換、線程切換的操作
//發送網絡請求(異步)call.enqueue(newCallback() {//請求成功時回調@OverridepublicvoidonResponse(Call call, Response response) {//請求處理,輸出結果response.body().show();? ? ? ? ? ? }//請求失敗時候的回調@OverridepublicvoidonFailure(Call call, Throwable throwable) {? ? ? ? ? ? ? ? System.out.println("連接失敗");? ? ? ? ? ? }? ? ? ? });// 發送網絡請求(同步)Response response = call.execute();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
通過response類的?body()對返回的數據進行處理
//發送網絡請求(異步)call.enqueue(newCallback() {//請求成功時回調@OverridepublicvoidonResponse(Call call, Response response) {// 對返回數據進行處理response.body().show();? ? ? ? ? ? }//請求失敗時候的回調@OverridepublicvoidonFailure(Call call, Throwable throwable) {? ? ? ? ? ? ? ? System.out.println("連接失敗");? ? ? ? ? ? }? ? ? ? });// 發送網絡請求(同步)Response response = call.execute();// 對返回數據進行處理response.body().show();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
接下來,我將用兩個實例分別對 Retrofit GET方式 和 POST方式進行 網絡請求 講解。
實現功能:將中文翻譯成英文
實現方案:采用Get方法對 金山詞霸API 發送網絡請求?
采用?Gson?進行數據解析
步驟說明
步驟1:添加Retrofit庫的依賴?
步驟2:創建 接收服務器返回數據 的類?
步驟3:創建 用于描述網絡請求 的接口?
步驟4:創建 Retrofit 實例?
步驟5:創建 網絡請求接口實例 并 配置網絡請求參數?
步驟6:發送網絡請求(采用最常用的異步方式)
封裝了 數據轉換、線程切換的操作
步驟7:?處理服務器返回的數據
接下來,我們一步步進行講解。
具體使用
1. 在?Gradle加入Retrofit庫的依賴
由于Retrofit是基于OkHttp,所以還需要添加OkHttp庫依賴
build.gradle
dependencies {? ? compile'com.squareup.retrofit2:retrofit:2.0.2'// Retrofit庫compile'com.squareup.okhttp3:okhttp:3.1.2'// Okhttp庫}
1
2
3
4
5
6
2. 添加 網絡權限?
AndroidManifest.xml
1
金山詞霸API 的數據格式說明如下:
//URL模板http://fy.iciba.com/ajax.php// URL實例http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world// 參數說明:// a:固定值 fy// f:原文內容類型,日語取 ja,中文取 zh,英語取 en,韓語取 ko,德語取 de,西班牙語取 es,法語取 fr,自動則取 auto// t:譯文內容類型,日語取 ja,中文取 zh,英語取 en,韓語取 ko,德語取 de,西班牙語取 es,法語取 fr,自動則取 auto// w:查詢內容
1
2
3
4
5
6
7
8
9
10
11
根據 金山詞霸API 的數據格式,創建 接收服務器返回數據 的類:
Translation.java
publicclassTranslation {privateintstatus;privatecontent content;privatestaticclasscontent {privateStringfrom;privateString to;privateString vendor;privateStringout;privateinterrNo;? ? }//定義 輸出返回數據 的方法publicvoidshow() {? ? ? ? System.out.println(status);? ? ? ? System.out.println(content.from);? ? ? ? System.out.println(content.to);? ? ? ? System.out.println(content.vendor);? ? ? ? System.out.println(content.out);? ? ? ? System.out.println(content.errNo);? ? }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
采用?注解?描述 網絡請求參數。?
GetRequest_Interface.java
publicinterfaceGetRequest_Interface { @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")? ? Call getCall();// 注解里傳入 網絡請求 的部分URL地址// Retrofit把網絡請求的URL分成了兩部分:一部分放在Retrofit對象里,另一部分放在網絡請求接口里// 如果接口里的url是一個完整的網址,那么放在Retrofit對象里的URL可以忽略// getCall()是接受網絡請求數據的方法}
1
2
3
4
5
6
7
8
9
接下來的步驟均在GetRequest.java內實現(看注釋)
步驟4:創建Retrofit對象?
步驟5:創建 網絡請求接口 的實例?
步驟6:發送網絡請求
以最常用的 異步請求 為例
步驟7:處理返回數據
GetRequest.java
publicclassGetRequestextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);? ? ? ? setContentView(R.layout.activity_main);? ? ? ? request();// 使用Retrofit封裝的方法}publicvoidrequest() {//步驟4:創建Retrofit對象Retrofit retrofit =newRetrofit.Builder()? ? ? ? ? ? ? ? .baseUrl("http://fy.iciba.com/")// 設置 網絡請求 Url.addConverterFactory(GsonConverterFactory.create())//設置使用Gson解析(記得加入依賴).build();// 步驟5:創建 網絡請求接口 的實例GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);//對 發送請求 進行封裝Call call = request.getCall();//步驟6:發送網絡請求(異步)call.enqueue(newCallback() {//請求成功時回調@OverridepublicvoidonResponse(Call call, Response response) {// 步驟7:處理返回的數據結果response.body().show();? ? ? ? ? ? }//請求失敗時回調@OverridepublicvoidonFailure(Call call, Throwable throwable) {? ? ? ? ? ? ? ? System.out.println("連接失敗");? ? ? ? ? ? }? ? ? ? });? ? }}
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
31
32
33
34
35
36
37
38
39
40
41
由于此處采用了 Gson 解析,所以需要在 Gradle加入依賴?
build.gradle
compile'com.squareup.retrofit2:converter-gson:2.0.2'
1
Carson_Ho的Github:https://github.com/Carson-Ho/RetrofitDemo
實現的功能:將 英文 翻譯成 中文
實現方法:采用Post方法對 有道API 發送網絡請求?
采用?Gson?進行數據解析
使用步驟
步驟1:添加Retrofit庫的依賴?
步驟2:創建 接收服務器返回數據 的類?
步驟3:創建 用于描述網絡請求 的接口?
步驟4:創建 Retrofit 實例?
步驟5:創建 網絡請求接口實例 并 配置網絡請求參數?
步驟6:發送網絡請求(采用最常用的異步方式)
封裝了 數據轉換、線程切換的操作
步驟7:?處理服務器返回的數據
接下來,我們一步步進行Retrofit的使用。
具體使用
1. 在?Gradle加入Retrofit庫的依賴
由于Retrofit是基于OkHttp,所以還需要添加OkHttp庫依賴
build.gradle
dependencies {? ? compile'com.squareup.retrofit2:retrofit:2.0.2'// Retrofit庫compile'com.squareup.okhttp3:okhttp:3.1.2'// Okhttp庫}
1
2
3
4
5
6
2. 添加 網絡權限?
AndroidManifest.xml
1
API 的數據格式說明如下:
//URLhttp://fanyi.youdao.com/translate// URL實例http://fanyi.youdao.com/translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=// 參數說明// doctype:json 或 xml// jsonversion:如果 doctype 值是 xml,則去除該值,若 doctype 值是 json,該值為空即可// xmlVersion:如果 doctype 值是 json,則去除該值,若 doctype 值是 xml,該值為空即可// type:語言自動檢測時為 null,為 null 時可為空。英譯中為 EN2ZH_CN,中譯英為 ZH_CN2EN,日譯中為 JA2ZH_CN,中譯日為 ZH_CN2JA,韓譯中為 KR2ZH_CN,中譯韓為 ZH_CN2KR,中譯法為 ZH_CN2FR,法譯中為 FR2ZH_CN// keyform:mdict. + 版本號 + .手機平臺。可為空// model:手機型號。可為空// mid:平臺版本。可為空// imei:???。可為空// vendor:應用下載平臺。可為空// screen:屏幕寬高。可為空// ssid:用戶名。可為空// abtest:???。可為空// 請求方式說明// 請求方式:POST// 請求體:i// 請求格式:x-www-form-urlencoded
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
根據 有道API 的數據格式,創建 接收服務器返回數據 的類:
Translation.java
publicclassTranslation1{privateString type;privateinterrorCode;privateintelapsedTime;privateList> translateResult;publicStringgetType() {returntype;? ? }publicvoidsetType(String type) {this.type = type;? ? }publicintgetErrorCode() {returnerrorCode;? ? }publicvoidsetErrorCode(interrorCode) {this.errorCode = errorCode;? ? }publicintgetElapsedTime() {returnelapsedTime;? ? }publicvoidsetElapsedTime(intelapsedTime) {this.elapsedTime = elapsedTime;? ? }publicList>getTranslateResult() {returntranslateResult;? ? }publicvoidsetTranslateResult(List> translateResult) {this.translateResult = translateResult;? ? }publicstaticclassTranslateResultBean{/**
? ? ? ? * src : merry me
? ? ? ? * tgt : 我快樂
? ? ? ? */publicString src;publicString tgt;publicStringgetSrc() {returnsrc;? ? ? ? }publicvoidsetSrc(String src) {this.src = src;? ? ? ? }publicStringgetTgt() {returntgt;? ? ? ? }publicvoidsetTgt(String tgt) {this.tgt = tgt;? ? ? ? }? ? }}
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
采用 注解 描述 網絡請求參數。
PostRequest_Interface.java
publicinterfacePostRequest_Interface{@POST("translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=")@FormUrlEncodedCall getCall(@Field("i") String targetSentence);//采用@Post表示Post方法進行請求(傳入部分url地址)// 采用@FormUrlEncoded注解的原因:API規定采用請求格式x-www-form-urlencoded,即表單形式// 需要配合@Field 向服務器提交需要的字段}
1
2
3
4
5
6
7
8
9
接下來的步驟均在PostRequest.java內實現(看注釋)
步驟4:創建Retrofit對象?
步驟5:創建 網絡請求接口 的實例?
步驟6:發送網絡請求
以最常用的 異步請求 為例
步驟7:處理返回數據
PostRequest.java
publicclassPostRequestextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);? ? ? ? setContentView(R.layout.activity_main);? ? ? ? request();? ? }publicvoidrequest() {//步驟4:創建Retrofit對象Retrofit retrofit =newRetrofit.Builder()? ? ? ? ? ? ? ? .baseUrl("http://fanyi.youdao.com/")// 設置 網絡請求 Url.addConverterFactory(GsonConverterFactory.create())//設置使用Gson解析(記得加入依賴).build();// 步驟5:創建 網絡請求接口 的實例PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);//對 發送請求 進行封裝(設置需要翻譯的內容)Call call = request.getCall("I love you");//步驟6:發送網絡請求(異步)call.enqueue(newCallback() {//請求成功時回調@OverridepublicvoidonResponse(Call call, Response response) {// 步驟7:處理返回的數據結果:輸出翻譯的內容System.out.println(response.body().getTranslateResult().get(0).get(0).getTgt());? ? ? ? ? ? }//請求失敗時回調@OverridepublicvoidonFailure(Call call, Throwable throwable) {? ? ? ? ? ? ? ? System.out.println("請求失敗");? ? ? ? ? ? ? ? System.out.println(throwable.getMessage());? ? ? ? ? ? }? ? ? ? });? ? }}
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
由于此處采用了 Gson 解析,所以需要在?Gradle?加入依賴?
build.gradle
compile'com.squareup.retrofit2:converter-gson:2.0.2'
1
Carson_Ho的Github:https://github.com/Carson-Ho/RetrofitDemo
Retrofit的使用場景非常豐富,如支持RxJava和Prototocobuff
具體設置也非常簡單 & 方便:
<-- 主要在創建Retrofit對象中設置 -->Retrofit retrofit = new Retrofit.Builder().baseUrl(""http://fanyi.youdao.com/"").addConverterFactory(ProtoConverterFactory.create()) // 支持Prototocobuff解析.addConverterFactory(GsonConverterFactory.create()) // 支持Gson解析.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava.build();
1
2
3
4
5
6
7
具體關于?RxJava的使用這里就不展開,請期待下篇關于?Rxjava的文章。
看完本文,相信你已經非常熟悉?Retrofit 2.0?的使用
如果你希望繼續閱讀?Retrofit 2.0?的源碼,請看我寫的文章:Android:手把手帶你深入剖析 Retrofit 2.0 源碼
接下來,我將繼續分析與 Retrofit 配合使用的?RxJava,有興趣可以繼續關注Carson_Ho的安卓開發筆記