前言
在Andrroid開發(fā)中,網(wǎng)絡(luò)請求十分常用
而在Android網(wǎng)絡(luò)請求庫中,Retrofit是當(dāng)下最熱的一個網(wǎng)絡(luò)請求庫
今天,我將獻(xiàn)上一份非常詳細(xì)Retrofit v2.0的使用教程,希望你們會喜歡。
如果對Retrofit v2.0的源碼感興趣,可看文章:Android:手把手帶你深入剖析 Retrofit 2.0 源碼
特別注意:
準(zhǔn)確來說,Retrofit 是一個 RESTful 的 HTTP 網(wǎng)絡(luò)請求框架的封裝。
原因:網(wǎng)絡(luò)請求的工作本質(zhì)上是?OkHttp?完成,而 Retrofit 僅負(fù)責(zé) 網(wǎng)絡(luò)請求接口的封裝
App應(yīng)用程序通過 Retrofit 請求網(wǎng)絡(luò),實際上是使用 Retrofit 接口層封裝請求參數(shù)、Header、Url 等信息,之后由 OkHttp 完成后續(xù)的請求操作
在服務(wù)端返回數(shù)據(jù)之后,OkHttp 將原始的結(jié)果交給 Retrofit,Retrofit根據(jù)用戶的需求對結(jié)果進(jìn)行解析
除了Retrofit,如今Android中主流的網(wǎng)絡(luò)請求框架有:
Android-Async-Http
Volley
OkHttp
下面是簡單介紹:
一圖讓你了解全部的網(wǎng)絡(luò)請求庫和他們之間的區(qū)別!
附:各個主流網(wǎng)絡(luò)請求庫的Github地址
使用 Retrofit 的步驟共有7個:
步驟1:添加Retrofit庫的依賴?
步驟2:創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類?
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請求 的接口?
步驟4:創(chuàng)建 Retrofit 實例?
步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口實例 并 配置網(wǎng)絡(luò)請求參數(shù)?
步驟6:發(fā)送網(wǎng)絡(luò)請求(異步 / 同步)
封裝了 數(shù)據(jù)轉(zhuǎn)換、線程切換的操作
步驟7:?處理服務(wù)器返回的數(shù)據(jù)
接下來,我們一步步進(jìn)行講解。
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. 添加 網(wǎng)絡(luò)權(quán)限?
AndroidManifest.xml
1
步驟2:創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類
Reception.java
public class Reception {...// 根據(jù)返回數(shù)據(jù)的格式和數(shù)據(jù)解析方式(Json、XML等)定義? ? // 下面會在實例進(jìn)行說明? ? ? ? }
1
2
3
4
5
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請求 的接口
Retrofit將 Http請求 抽象成 Java接口:采用?注解?描述網(wǎng)絡(luò)請求參數(shù) 和配置網(wǎng)絡(luò)請求參數(shù)?
用 動態(tài)代理 動態(tài) 將該接口的注解“翻譯”成一個 Http 請求,最后再執(zhí)行 Http 請求?
注:接口中的每個方法的參數(shù)都需要使用注解標(biāo)注,否則會報錯
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方法發(fā)送網(wǎng)絡(luò)請求// getCall() = 接收網(wǎng)絡(luò)請求數(shù)據(jù)的方法// 其中返回類型為Call<*>,*是接收數(shù)據(jù)的類(即上面定義的Translation類)// 如果想直接獲得Responsebody中的內(nèi)容,可以定義網(wǎng)絡(luò)請求返回值為Call<ResponseBody>}
1
2
3
4
5
6
7
8
9
10
下面詳細(xì)介紹Retrofit 網(wǎng)絡(luò)請求接口 的注解類型。
第一類:網(wǎng)絡(luò)請求方法
詳細(xì)說明:?
a. @GET、@POST、@PUT、@DELETE、@HEAD?
以上方法分別對應(yīng) HTTP中的網(wǎng)絡(luò)請求方式
publicinterfaceGetRequest_Interface {? ? @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")? ? Call? getCall();// @GET注解的作用:采用Get方法發(fā)送網(wǎng)絡(luò)請求// getCall() = 接收網(wǎng)絡(luò)請求數(shù)據(jù)的方法// 其中返回類型為Call<*>,*是接收數(shù)據(jù)的類(即上面定義的Translation類)}
1
2
3
4
5
6
7
8
此處特意說明URL的組成:Retrofit把 網(wǎng)絡(luò)請求的URL 分成了兩部分設(shè)置:
// 第1部分:在網(wǎng)絡(luò)請求接口的注解設(shè)置@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")Call? getCall();// 第2部分:在創(chuàng)建Retrofit實例時通過.baseUrl()設(shè)置Retrofit retrofit =newRetrofit.Builder()? ? ? ? ? ? ? ? .baseUrl("http://fanyi.youdao.com/")//設(shè)置網(wǎng)絡(luò)請求的Url地址.addConverterFactory(GsonConverterFactory.create())//設(shè)置數(shù)據(jù)解析器.build();// 從上面看出:一個請求的URL可以通過 替換塊 和 請求方法的參數(shù) 來進(jìn)行動態(tài)的URL更新。// 替換塊是由 被{}包裹起來的字符串構(gòu)成// 即:Retrofit支持動態(tài)改變網(wǎng)絡(luò)請求根目錄
1
2
3
4
5
6
7
8
9
10
11
12
13
網(wǎng)絡(luò)請求的完整 Url =在創(chuàng)建Retrofit實例時通過.baseUrl()設(shè)置 +網(wǎng)絡(luò)請求接口的注解設(shè)置(下面稱 “path“ )
具體整合的規(guī)則如下:
建議采用第三種方式來配置,并盡量使用同一種路徑形式。
b. @HTTP
作用:替換@GET、@POST、@PUT、@DELETE、@HEAD注解的作用 及 更多功能拓展
具體使用:通過屬性method、path、hasBody進(jìn)行設(shè)置
publicinterfaceGetRequest_Interface{/**
? ? * method:網(wǎng)絡(luò)請求的方法(區(qū)分大小寫)
? ? * path:網(wǎng)絡(luò)請求地址路徑
? ? * hasBody:是否有請求體
? ? */@HTTP(method ="GET", path ="blog/{id}", hasBody =false)? ? Call getCall(@Path("id")intid);// {id} 表示是一個變量// method 的值 retrofit 不會做處理,所以要自行保證準(zhǔn)確}
1
2
3
4
5
6
7
8
9
10
11
a. @FormUrlEncoded
作用:表示發(fā)送form-encoded的數(shù)據(jù)
每個鍵值對需要用@Filed來注解鍵名,隨后的對象需要提供值。
b. @Multipart
作用:表示發(fā)送form-encoded的數(shù)據(jù)(適用于 有文件 上傳的場景)?
每個鍵值對需要用@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} 中已經(jīng)包含了表單字段的信息),? ? ? ? */@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
詳細(xì)說明
a. @Header & @Headers
作用:添加請求頭 &添加不固定的請求頭
具體使用如下:
// @Header@GET("user")Call getUser(@Header("Authorization") String authorization)// @Headers@Headers("Authorization: authorization")@GET("user")Call getUser()// 以上的效果是一致的。// 區(qū)別在于使用場景和使用方式// 1. 使用場景:@Header用于添加不固定的請求頭,@Headers用于添加固定的請求頭// 2. 使用方式:@Header作用于方法的參數(shù);@Headers作用于方法
1
2
3
4
5
6
7
8
9
10
11
12
13
b. @Body
作用:以?Post方式 傳遞 自定義數(shù)據(jù)類型 給服務(wù)器
特別注意:如果提交的是一個Map,那么作用相當(dāng)于?@Field?
不過Map要經(jīng)過?FormBody.Builder?類處理成為符合 Okhttp 格式的表單,如:
FormBody.Builderbuilder = new FormBody.Builder();builder.add("key","value");
1
2
3
c. @Field & @FieldMap
作用:發(fā)送 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// 實現(xiàn)的效果與上面相同,但要傳入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
作用:發(fā)送 Post請求 時提交請求的表單字段
與@Field的區(qū)別:功能相同,但攜帶的參數(shù)類型更加豐富,包括數(shù)據(jù)流,所以適用于 有文件上傳 的場景
具體使用:與?@Multipart?注解配合使用
public interface GetRequest_Interface {/**? ? ? ? * {@linkPart} 后面支持三種類型,{@linkRequestBody}、{@linkokhttp3.MultipartBody.Part} 、任意類型? ? ? ? * 除 {@linkokhttp3.MultipartBody.Part} 以外,其它類型都必須帶上表單字段({@linkokhttp3.MultipartBody.Part} 中已經(jīng)包含了表單字段的信息),? ? ? ? */@POST("/form")@MultipartCall testFileUpload1(@Part("name") RequestBody name,@Part("age") RequestBody age,@PartMultipartBody.Part file);/**? ? ? ? * PartMap 注解支持一個Map作為參數(shù),支持 {@linkRequestBody } 類型,? ? ? ? * 如果有其它的類型,會被{@linkretrofit2.Converter}轉(zhuǎn)換,如后面會介紹的 使用{@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"),"這里是模擬文件的內(nèi)容");// @PartMultipartBody.Part filePart = MultipartBody.Part.createFormData("file","test.txt", file);? ? ? ? Call call3 = service.testFileUpload1(name, age, filePart);? ? ? ? ResponseBodyPrinter.printResponseBody(call3);// @PartMap// 實現(xiàn)和上面同樣的效果Map fileUpload2Args =newHashMap<>();? ? ? ? fileUpload2Args.put("name", name);? ? ? ? fileUpload2Args.put("age", age);//這里并不會被當(dāng)成文件,因為沒有文件名(包含在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?方法的查詢參數(shù)(Query = Url 中 ‘?’ 后面的 key-value)
如:url =?http://www.println.net/?cate=android,其中,Query = cate
具體使用:配置時只需要在接口方法中增加一個參數(shù)即可:
@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// 在發(fā)起請求時, {user} 會被替換為方法的第一個參數(shù) user(被@Path注解作用)}
1
2
3
4
5
6
7
g. @Url
作用:直接傳入一個請求的 URL變量 用于URL設(shè)置
具體使用:
publicinterfaceGetRequest_Interface{@GETCall testUrlAndQuery(@UrlString url,@Query("showAll")booleanshowAll);// 當(dāng)有URL注解時,@GET傳入的URL就可以省略// 當(dāng)GET、POST...HTTP等方法中沒有設(shè)置Url時,則必須使用 {@link Url}提供}
1
2
3
4
5
6
7
8
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://fanyi.youdao.com/") // 設(shè)置網(wǎng)絡(luò)請求的Url地址.addConverterFactory(GsonConverterFactory.create()) // 設(shè)置數(shù)據(jù)解析器.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺.build();
1
2
3
4
5
a. 關(guān)于數(shù)據(jù)解析器(Converter)
Retrofit支持多種數(shù)據(jù)解析方式
使用時需要在Gradle添加依賴
數(shù)據(jù)解析器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
b. 關(guān)于網(wǎng)絡(luò)請求適配器(CallAdapter)
Retrofit支持多種網(wǎng)絡(luò)請求適配器方式:guava、Java8和rxjava?
使用時如使用的是?Android?默認(rèn)的?CallAdapter,則不需要添加網(wǎng)絡(luò)請求適配器的依賴,否則則需要按照需求進(jìn)行添加?
Retrofit 提供的?CallAdapter
使用時需要在Gradle添加依賴:
網(wǎng)絡(luò)請求適配器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
步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口實例
// 創(chuàng)建 網(wǎng)絡(luò)請求接口 的實例? ? ? ? GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);//對 發(fā)送請求 進(jìn)行封裝Callcall= request.getCall();
1
2
3
4
5
步驟6:發(fā)送網(wǎng)絡(luò)請求(異步 / 同步)
封裝了 數(shù)據(jù)轉(zhuǎn)換、線程切換的操作
//發(fā)送網(wǎng)絡(luò)請求(異步)call.enqueue(newCallback() {//請求成功時回調(diào)@OverridepublicvoidonResponse(Call call, Response response) {//請求處理,輸出結(jié)果response.body().show();? ? ? ? ? ? }//請求失敗時候的回調(diào)@OverridepublicvoidonFailure(Call call, Throwable throwable) {? ? ? ? ? ? ? ? System.out.println("連接失敗");? ? ? ? ? ? }? ? ? ? });// 發(fā)送網(wǎng)絡(luò)請求(同步)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()對返回的數(shù)據(jù)進(jìn)行處理
//發(fā)送網(wǎng)絡(luò)請求(異步)call.enqueue(newCallback() {//請求成功時回調(diào)@OverridepublicvoidonResponse(Call call, Response response) {// 對返回數(shù)據(jù)進(jìn)行處理response.body().show();? ? ? ? ? ? }//請求失敗時候的回調(diào)@OverridepublicvoidonFailure(Call call, Throwable throwable) {? ? ? ? ? ? ? ? System.out.println("連接失敗");? ? ? ? ? ? }? ? ? ? });// 發(fā)送網(wǎng)絡(luò)請求(同步)Response response = call.execute();// 對返回數(shù)據(jù)進(jìn)行處理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方式進(jìn)行 網(wǎng)絡(luò)請求 講解。
實現(xiàn)功能:將中文翻譯成英文
實現(xiàn)方案:采用Get方法對 金山詞霸API 發(fā)送網(wǎng)絡(luò)請求?
采用?Gson?進(jìn)行數(shù)據(jù)解析
步驟說明
步驟1:添加Retrofit庫的依賴?
步驟2:創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類?
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請求 的接口?
步驟4:創(chuàng)建 Retrofit 實例?
步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口實例 并 配置網(wǎng)絡(luò)請求參數(shù)?
步驟6:發(fā)送網(wǎng)絡(luò)請求(采用最常用的異步方式)
封裝了 數(shù)據(jù)轉(zhuǎn)換、線程切換的操作
步驟7:?處理服務(wù)器返回的數(shù)據(jù)
接下來,我們一步步進(jìn)行講解。
具體使用
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. 添加 網(wǎng)絡(luò)權(quán)限?
AndroidManifest.xml
1
步驟2:創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類
金山詞霸API 的數(shù)據(jù)格式說明如下:
//URL模板http://fy.iciba.com/ajax.php// URL實例http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world// 參數(shù)說明:// a:固定值 fy// f:原文內(nèi)容類型,日語取 ja,中文取 zh,英語取 en,韓語取 ko,德語取 de,西班牙語取 es,法語取 fr,自動則取 auto// t:譯文內(nèi)容類型,日語取 ja,中文取 zh,英語取 en,韓語取 ko,德語取 de,西班牙語取 es,法語取 fr,自動則取 auto// w:查詢內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
根據(jù) 金山詞霸API 的數(shù)據(jù)格式,創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類:
Translation.java
publicclassTranslation {privateintstatus;privatecontent content;privatestaticclasscontent {privateStringfrom;privateString to;privateString vendor;privateStringout;privateinterrNo;? ? }//定義 輸出返回數(shù)據(jù) 的方法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
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請求 的接口
采用?注解?描述 網(wǎng)絡(luò)請求參數(shù)。?
GetRequest_Interface.java
publicinterfaceGetRequest_Interface { @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")? ? Call getCall();// 注解里傳入 網(wǎng)絡(luò)請求 的部分URL地址// Retrofit把網(wǎng)絡(luò)請求的URL分成了兩部分:一部分放在Retrofit對象里,另一部分放在網(wǎng)絡(luò)請求接口里// 如果接口里的url是一個完整的網(wǎng)址,那么放在Retrofit對象里的URL可以忽略// getCall()是接受網(wǎng)絡(luò)請求數(shù)據(jù)的方法}
1
2
3
4
5
6
7
8
9
接下來的步驟均在GetRequest.java內(nèi)實現(xiàn)(看注釋)
步驟4:創(chuàng)建Retrofit對象?
步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口 的實例?
步驟6:發(fā)送網(wǎng)絡(luò)請求
以最常用的 異步請求 為例
步驟7:處理返回數(shù)據(jù)
GetRequest.java
publicclassGetRequestextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);? ? ? ? setContentView(R.layout.activity_main);? ? ? ? request();// 使用Retrofit封裝的方法}publicvoidrequest() {//步驟4:創(chuàng)建Retrofit對象Retrofit retrofit =newRetrofit.Builder()? ? ? ? ? ? ? ? .baseUrl("http://fy.iciba.com/")// 設(shè)置 網(wǎng)絡(luò)請求 Url.addConverterFactory(GsonConverterFactory.create())//設(shè)置使用Gson解析(記得加入依賴).build();// 步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口 的實例GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);//對 發(fā)送請求 進(jìn)行封裝Call call = request.getCall();//步驟6:發(fā)送網(wǎng)絡(luò)請求(異步)call.enqueue(newCallback() {//請求成功時回調(diào)@OverridepublicvoidonResponse(Call call, Response response) {// 步驟7:處理返回的數(shù)據(jù)結(jié)果response.body().show();? ? ? ? ? ? }//請求失敗時回調(diào)@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
實現(xiàn)的功能:將 英文 翻譯成 中文
實現(xiàn)方法:采用Post方法對 有道API 發(fā)送網(wǎng)絡(luò)請求?
采用?Gson?進(jìn)行數(shù)據(jù)解析
使用步驟
步驟1:添加Retrofit庫的依賴?
步驟2:創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類?
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請求 的接口?
步驟4:創(chuàng)建 Retrofit 實例?
步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口實例 并 配置網(wǎng)絡(luò)請求參數(shù)?
步驟6:發(fā)送網(wǎng)絡(luò)請求(采用最常用的異步方式)
封裝了 數(shù)據(jù)轉(zhuǎn)換、線程切換的操作
步驟7:?處理服務(wù)器返回的數(shù)據(jù)
接下來,我們一步步進(jìn)行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. 添加 網(wǎng)絡(luò)權(quán)限?
AndroidManifest.xml
1
步驟2:創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類
API 的數(shù)據(jù)格式說明如下:
//URLhttp://fanyi.youdao.com/translate// URL實例http://fanyi.youdao.com/translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=// 參數(shù)說明// 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:應(yīng)用下載平臺。可為空// 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
根據(jù) 有道API 的數(shù)據(jù)格式,創(chuàng)建 接收服務(wù)器返回數(shù)據(jù) 的類:
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
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請求 的接口
采用 注解 描述 網(wǎng)絡(luò)請求參數(shù)。
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方法進(jìn)行請求(傳入部分url地址)// 采用@FormUrlEncoded注解的原因:API規(guī)定采用請求格式x-www-form-urlencoded,即表單形式// 需要配合@Field 向服務(wù)器提交需要的字段}
1
2
3
4
5
6
7
8
9
接下來的步驟均在PostRequest.java內(nèi)實現(xiàn)(看注釋)
步驟4:創(chuàng)建Retrofit對象?
步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口 的實例?
步驟6:發(fā)送網(wǎng)絡(luò)請求
以最常用的 異步請求 為例
步驟7:處理返回數(shù)據(jù)
PostRequest.java
publicclassPostRequestextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);? ? ? ? setContentView(R.layout.activity_main);? ? ? ? request();? ? }publicvoidrequest() {//步驟4:創(chuàng)建Retrofit對象Retrofit retrofit =newRetrofit.Builder()? ? ? ? ? ? ? ? .baseUrl("http://fanyi.youdao.com/")// 設(shè)置 網(wǎng)絡(luò)請求 Url.addConverterFactory(GsonConverterFactory.create())//設(shè)置使用Gson解析(記得加入依賴).build();// 步驟5:創(chuàng)建 網(wǎng)絡(luò)請求接口 的實例PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);//對 發(fā)送請求 進(jìn)行封裝(設(shè)置需要翻譯的內(nèi)容)Call call = request.getCall("I love you");//步驟6:發(fā)送網(wǎng)絡(luò)請求(異步)call.enqueue(newCallback() {//請求成功時回調(diào)@OverridepublicvoidonResponse(Call call, Response response) {// 步驟7:處理返回的數(shù)據(jù)結(jié)果:輸出翻譯的內(nèi)容System.out.println(response.body().getTranslateResult().get(0).get(0).getTgt());? ? ? ? ? ? }//請求失敗時回調(diào)@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
具體設(shè)置也非常簡單 & 方便:
<-- 主要在創(chuàng)建Retrofit對象中設(shè)置 -->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
具體關(guān)于?RxJava的使用這里就不展開,請期待下篇關(guān)于?Rxjava的文章。
看完本文,相信你已經(jīng)非常熟悉?Retrofit 2.0?的使用
如果你希望繼續(xù)閱讀?Retrofit 2.0?的源碼,請看我寫的文章:Android:手把手帶你深入剖析 Retrofit 2.0 源碼
接下來,我將繼續(xù)分析與 Retrofit 配合使用的?RxJava,有興趣可以繼續(xù)關(guān)注Carson_Ho的安卓開發(fā)筆記