文章來自:https://blog.csdn.net/carson_ho/article/details/73732076
前言
- 在
Andrroid
開發(fā)中樊诺,網(wǎng)絡(luò)請(qǐng)求十分常用 - 而在
Android
網(wǎng)絡(luò)請(qǐng)求庫中,Retrofit
是當(dāng)下最熱的一個(gè)網(wǎng)絡(luò)請(qǐng)求庫
- 今天音同,我將獻(xiàn)上一份非常詳細(xì)
Retrofit v2.0
的使用教程词爬,希望你們會(huì)喜歡。
如果對(duì)
Retrofit v2.0
的源碼感興趣瘟斜,可看文章:Android:手把手帶你深入剖析 Retrofit 2.0 源碼
目錄
1. 簡介
特別注意:
- 準(zhǔn)確來說缸夹,Retrofit 是一個(gè) RESTful 的 HTTP 網(wǎng)絡(luò)請(qǐng)求框架的封裝。
- 原因:網(wǎng)絡(luò)請(qǐng)求的工作本質(zhì)上是
OkHttp
完成螺句,而 Retrofit 僅負(fù)責(zé) 網(wǎng)絡(luò)請(qǐng)求接口的封裝
- App應(yīng)用程序通過 Retrofit 請(qǐng)求網(wǎng)絡(luò)虽惭,實(shí)際上是使用 Retrofit 接口層封裝請(qǐng)求參數(shù)、Header蛇尚、Url 等信息芽唇,之后由 OkHttp 完成后續(xù)的請(qǐng)求操作
- 在服務(wù)端返回?cái)?shù)據(jù)之后,OkHttp 將原始的結(jié)果交給 Retrofit,Retrofit根據(jù)用戶的需求對(duì)結(jié)果進(jìn)行解析
2. 與其他開源請(qǐng)求庫對(duì)比
除了Retrofit匆笤,如今Android中主流的網(wǎng)絡(luò)請(qǐng)求框架有:
- Android-Async-Http
- Volley
- OkHttp
下面是簡單介紹:
一圖讓你了解全部的網(wǎng)絡(luò)請(qǐng)求庫和他們之間的區(qū)別研侣!
附:各個(gè)主流網(wǎng)絡(luò)請(qǐng)求庫的Github地址
3. 使用介紹
使用 Retrofit 的步驟共有7個(gè):
步驟1:添加Retrofit庫的依賴
步驟2:創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請(qǐng)求 的接口
步驟4:創(chuàng)建 Retrofit 實(shí)例
步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口實(shí)例 并 配置網(wǎng)絡(luò)請(qǐng)求參數(shù)
步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步 / 同步)
封裝了 數(shù)據(jù)轉(zhuǎn)換、線程切換的操作
**步驟7: **處理服務(wù)器返回的數(shù)據(jù)
接下來炮捧,我們一步步進(jìn)行講解庶诡。
步驟1:添加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庫
}
2. 添加 網(wǎng)絡(luò)權(quán)限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
步驟2:創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類
Reception.java
public class Reception {
...
// 根據(jù)返回?cái)?shù)據(jù)的格式和數(shù)據(jù)解析方式(Json咆课、XML等)定義
// 下面會(huì)在實(shí)例進(jìn)行說明
}
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請(qǐng)求 的接口
-
Retrofit將 Http請(qǐng)求 抽象成 Java接口:采用 注解 描述網(wǎng)絡(luò)請(qǐng)求參數(shù) 和配置網(wǎng)絡(luò)請(qǐng)求參數(shù)
用 動(dòng)態(tài)代理 動(dòng)態(tài) 將該接口的注解“翻譯”成一個(gè) Http 請(qǐng)求末誓,最后再執(zhí)行 Http 請(qǐng)求
注:接口中的每個(gè)方法的參數(shù)都需要使用注解標(biāo)注,否則會(huì)報(bào)錯(cuò)
GetRequest_Interface.interface
public interface GetRequest_Interface {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation> getCall();
// @GET注解的作用:采用Get方法發(fā)送網(wǎng)絡(luò)請(qǐng)求
// getCall() = 接收網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)的方法
// 其中返回類型為Call<*>书蚪,*是接收數(shù)據(jù)的類(即上面定義的Translation類)
// 如果想直接獲得Responsebody中的內(nèi)容喇澡,可以定義網(wǎng)絡(luò)請(qǐng)求返回值為Call<ResponseBody>
}
下面詳細(xì)介紹Retrofit 網(wǎng)絡(luò)請(qǐng)求接口 的注解類型。
注解類型
注解說明
第一類:網(wǎng)絡(luò)請(qǐng)求方法
詳細(xì)說明:
a. @GET殊校、@POST晴玖、@PUT、@DELETE为流、@HEAD
以上方法分別對(duì)應(yīng) HTTP中的網(wǎng)絡(luò)請(qǐng)求方式
public interface GetRequest_Interface {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation> getCall();
// @GET注解的作用:采用Get方法發(fā)送網(wǎng)絡(luò)請(qǐng)求
// getCall() = 接收網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)的方法
// 其中返回類型為Call<*>呕屎,*是接收數(shù)據(jù)的類(即上面定義的Translation類)
}
此處特意說明URL的組成:Retrofit把 網(wǎng)絡(luò)請(qǐng)求的URL 分成了兩部分設(shè)置:
// 第1部分:在網(wǎng)絡(luò)請(qǐng)求接口的注解設(shè)置
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation> getCall();
// 第2部分:在創(chuàng)建Retrofit實(shí)例時(shí)通過.baseUrl()設(shè)置
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") //設(shè)置網(wǎng)絡(luò)請(qǐng)求的Url地址
.addConverterFactory(GsonConverterFactory.create()) //設(shè)置數(shù)據(jù)解析器
.build();
// 從上面看出:一個(gè)請(qǐng)求的URL可以通過 替換塊 和 請(qǐng)求方法的參數(shù) 來進(jìn)行動(dòng)態(tài)的URL更新。
// 替換塊是由 被{}包裹起來的字符串構(gòu)成
// 即:Retrofit支持動(dòng)態(tài)改變網(wǎng)絡(luò)請(qǐng)求根目錄
- 網(wǎng)絡(luò)請(qǐng)求的完整 Url =在創(chuàng)建Retrofit實(shí)例時(shí)通過.baseUrl()設(shè)置 +網(wǎng)絡(luò)請(qǐng)求接口的注解設(shè)置(下面稱 “path“ )
- 具體整合的規(guī)則如下:
建議采用第三種方式來配置艺谆,并盡量使用同一種路徑形式榨惰。
b. @HTTP
- 作用:替換@GET、@POST静汤、@PUT、@DELETE居凶、@HEAD注解的作用 及 更多功能拓展
- 具體使用:通過屬性method虫给、path、hasBody進(jìn)行設(shè)置
public interface GetRequest_Interface {
/**
* method:網(wǎng)絡(luò)請(qǐng)求的方法(區(qū)分大小寫)
* path:網(wǎng)絡(luò)請(qǐng)求地址路徑
* hasBody:是否有請(qǐng)求體
*/
@HTTP(method = "GET", path = "blog/{id}", hasBody = false)
Call<ResponseBody> getCall(@Path("id") int id);
// {id} 表示是一個(gè)變量
// method 的值 retrofit 不會(huì)做處理侠碧,所以要自行保證準(zhǔn)確
}
第二類:標(biāo)記
a. @FormUrlEncoded
- 作用:表示發(fā)送form-encoded的數(shù)據(jù)
每個(gè)鍵值對(duì)需要用@Filed來注解鍵名抹估,隨后的對(duì)象需要提供值。
b. @Multipart
- 作用:表示發(fā)送form-encoded的數(shù)據(jù)(適用于 有文件 上傳的場(chǎng)景)
每個(gè)鍵值對(duì)需要用@Part來注解鍵名弄兜,隨后的對(duì)象需要提供值药蜻。
具體使用如下:
GetRequest_Interface
public interface GetRequest_Interface {
/**
*表明是一個(gè)表單格式的請(qǐng)求(Content-Type:application/x-www-form-urlencoded)
* <code>Field("username")</code> 表示將后面的 <code>String name</code> 中name的取值作為 username 的值
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
/**
* {@link Part} 后面支持三種類型,{@link RequestBody}替饿、{@link okhttp3.MultipartBody.Part} 语泽、任意類型
* 除 {@link okhttp3.MultipartBody.Part} 以外,其它類型都必須帶上表單字段({@link okhttp3.MultipartBody.Part} 中已經(jīng)包含了表單字段的信息)视卢,
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
}
// 具體使用
GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
// @FormUrlEncoded
Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);
// @Multipart
RequestBody name = RequestBody.create(textType, "Carson");
RequestBody age = RequestBody.create(textType, "24");
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
第三類:網(wǎng)絡(luò)請(qǐng)求參數(shù)
詳細(xì)說明
a. @Header & @Headers
- 作用:添加請(qǐng)求頭 &添加不固定的請(qǐng)求頭
- 具體使用如下:
// @Header
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
// @Headers
@Headers("Authorization: authorization")
@GET("user")
Call<User> getUser()
// 以上的效果是一致的踱卵。
// 區(qū)別在于使用場(chǎng)景和使用方式
// 1\. 使用場(chǎng)景:@Header用于添加不固定的請(qǐng)求頭,@Headers用于添加固定的請(qǐng)求頭
// 2\. 使用方式:@Header作用于方法的參數(shù)据过;@Headers作用于方法
b. @Body
- 作用:以
Post
方式 傳遞 自定義數(shù)據(jù)類型 給服務(wù)器 - 特別注意:如果提交的是一個(gè)Map惋砂,那么作用相當(dāng)于
@Field
不過Map要經(jīng)過
FormBody.Builder
類處理成為符合 Okhttp 格式的表單妒挎,如:
FormBody.Builder builder = new FormBody.Builder();
builder.add("key","value");
c. @Field & @FieldMap
- 作用:發(fā)送 Post請(qǐng)求 時(shí)提交請(qǐng)求的表單字段
- 具體使用:與
@FormUrlEncoded
注解配合使用
public interface GetRequest_Interface {
/**
*表明是一個(gè)表單格式的請(qǐng)求(Content-Type:application/x-www-form-urlencoded)
* <code>Field("username")</code> 表示將后面的 <code>String name</code> 中name的取值作為 username 的值
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
/**
* Map的key作為表單的鍵
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);
}
// 具體使用
// @Field
Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);
// @FieldMap
// 實(shí)現(xiàn)的效果與上面相同,但要傳入Map
Map<String, Object> map = new HashMap<>();
map.put("username", "Carson");
map.put("age", 24);
Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);
d. @Part & @PartMap
-
作用:發(fā)送 Post請(qǐng)求 時(shí)提交請(qǐng)求的表單字段
與@Field的區(qū)別:功能相同西饵,但攜帶的參數(shù)類型更加豐富酝掩,包括數(shù)據(jù)流,所以適用于 有文件上傳 的場(chǎng)景
具體使用:與
@Multipart
注解配合使用
public interface GetRequest_Interface {
/**
* {@link Part} 后面支持三種類型眷柔,{@link RequestBody}庸队、{@link okhttp3.MultipartBody.Part} 、任意類型
* 除 {@link okhttp3.MultipartBody.Part} 以外闯割,其它類型都必須帶上表單字段({@link okhttp3.MultipartBody.Part} 中已經(jīng)包含了表單字段的信息)彻消,
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
/**
* PartMap 注解支持一個(gè)Map作為參數(shù),支持 {@link RequestBody } 類型宙拉,
* 如果有其它的類型宾尚,會(huì)被{@link retrofit2.Converter}轉(zhuǎn)換,如后面會(huì)介紹的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter}
* 所以{@link MultipartBody.Part} 就不適用了,所以文件只能用<b> @Part MultipartBody.Part </b>
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file);
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> 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)容");
// @Part
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
ResponseBodyPrinter.printResponseBody(call3);
// @PartMap
// 實(shí)現(xiàn)和上面同樣的效果
Map<String, RequestBody> fileUpload2Args = new HashMap<>();
fileUpload2Args.put("name", name);
fileUpload2Args.put("age", age);
//這里并不會(huì)被當(dāng)成文件谢澈,因?yàn)闆]有文件名(包含在Content-Disposition請(qǐng)求頭中)煌贴,但上面的 filePart 有
//fileUpload2Args.put("file", file);
Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //單獨(dú)處理文件
ResponseBodyPrinter.printResponseBody(call4);
}
e. @Query和@QueryMap
-
作用:用于
@GET
方法的查詢參數(shù)(Query = Url 中 ‘?’ 后面的 key-value)如:url = http://www.println.net/?cate=android,其中锥忿,Query = cate
具體使用:配置時(shí)只需要在接口方法中增加一個(gè)參數(shù)即可:
@GET("/")
Call<String> cate(@Query("cate") String cate);
}
// 其使用方式同 @Field與@FieldMap牛郑,這里不作過多描述
f. @Path
- 作用:URL地址的缺省值
- 具體使用:
public interface GetRequest_Interface {
@GET("users/{user}/repos")
Call<ResponseBody> getBlog(@Path("user") String user );
// 訪問的API是:https://api.github.com/users/{user}/repos
// 在發(fā)起請(qǐng)求時(shí), {user} 會(huì)被替換為方法的第一個(gè)參數(shù) user(被@Path注解作用)
}
g. @Url
- 作用:直接傳入一個(gè)請(qǐng)求的 URL變量 用于URL設(shè)置
- 具體使用:
public interface GetRequest_Interface {
@GET
Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
// 當(dāng)有URL注解時(shí)敬鬓,@GET傳入的URL就可以省略
// 當(dāng)GET淹朋、POST...HTTP等方法中沒有設(shè)置Url時(shí),則必須使用 {@link Url}提供
}
匯總
步驟4:創(chuàng)建 Retrofit 實(shí)例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") // 設(shè)置網(wǎng)絡(luò)請(qǐng)求的Url地址
.addConverterFactory(GsonConverterFactory.create()) // 設(shè)置數(shù)據(jù)解析器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺(tái)
.build();
a. 關(guān)于數(shù)據(jù)解析器(Converter)
- Retrofit支持多種數(shù)據(jù)解析方式
- 使用時(shí)需要在Gradle添加依賴
數(shù)據(jù)解析器 | Gradle依賴 |
---|---|
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 |
b. 關(guān)于網(wǎng)絡(luò)請(qǐng)求適配器(CallAdapter)
-
Retrofit支持多種網(wǎng)絡(luò)請(qǐng)求適配器方式:guava钉答、Java8和rxjava
使用時(shí)如使用的是
Android
默認(rèn)的CallAdapter
础芍,則不需要添加網(wǎng)絡(luò)請(qǐng)求適配器的依賴,否則則需要按照需求進(jìn)行添加
Retrofit 提供的CallAdapter
使用時(shí)需要在Gradle添加依賴:
網(wǎng)絡(luò)請(qǐng)求適配器 | Gradle依賴 |
---|---|
guava | com.squareup.retrofit2:adapter-guava:2.0.2 |
Java8 | com.squareup.retrofit2:adapter-java8:2.0.2 |
rxjava | com.squareup.retrofit2:adapter-rxjava:2.0.2 |
步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口實(shí)例
// 創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口 的實(shí)例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//對(duì) 發(fā)送請(qǐng)求 進(jìn)行封裝
Call<Reception> call = request.getCall();
步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步 / 同步)
封裝了 數(shù)據(jù)轉(zhuǎn)換数尿、線程切換的操作
//發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步)
call.enqueue(new Callback<Translation>() {
//請(qǐng)求成功時(shí)回調(diào)
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
//請(qǐng)求處理,輸出結(jié)果
response.body().show();
}
//請(qǐng)求失敗時(shí)候的回調(diào)
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("連接失敗");
}
});
// 發(fā)送網(wǎng)絡(luò)請(qǐng)求(同步)
Response<Reception> response = call.execute();
步驟7:處理返回?cái)?shù)據(jù)
通過response
類的 body()
對(duì)返回的數(shù)據(jù)進(jìn)行處理
//發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步)
call.enqueue(new Callback<Translation>() {
//請(qǐng)求成功時(shí)回調(diào)
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
// 對(duì)返回?cái)?shù)據(jù)進(jìn)行處理
response.body().show();
}
//請(qǐng)求失敗時(shí)候的回調(diào)
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("連接失敗");
}
});
// 發(fā)送網(wǎng)絡(luò)請(qǐng)求(同步)
Response<Reception> response = call.execute();
// 對(duì)返回?cái)?shù)據(jù)進(jìn)行處理
response.body().show();
4. 實(shí)例講解
接下來仑性,我將用兩個(gè)實(shí)例分別對(duì) Retrofit GET方式 和 POST方式進(jìn)行 網(wǎng)絡(luò)請(qǐng)求 講解。
4.1 實(shí)例1
實(shí)現(xiàn)功能:將中文翻譯成英文
-
實(shí)現(xiàn)方案:采用
Get
方法對(duì) 金山詞霸API 發(fā)送網(wǎng)絡(luò)請(qǐng)求采用
Gson
進(jìn)行數(shù)據(jù)解析
- 步驟說明
步驟1:添加Retrofit庫的依賴
步驟2:創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請(qǐng)求 的接口
步驟4:創(chuàng)建 Retrofit 實(shí)例
步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口實(shí)例 并 配置網(wǎng)絡(luò)請(qǐng)求參數(shù)
步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(采用最常用的異步方式)
封裝了 數(shù)據(jù)轉(zhuǎn)換右蹦、線程切換的操作
**步驟7: **處理服務(wù)器返回的數(shù)據(jù)
接下來诊杆,我們一步步進(jìn)行講解。
- 具體使用
步驟1:添加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庫
}
2. 添加 網(wǎng)絡(luò)權(quán)限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
步驟2:創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類
- 金山詞霸API 的數(shù)據(jù)格式說明如下:
// URL模板
http://fy.iciba.com/ajax.php
// URL實(shí)例
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朦乏,自動(dòng)則取 auto
// t:譯文內(nèi)容類型,日語取 ja氧骤,中文取 zh呻疹,英語取 en,韓語取 ko筹陵,德語取 de刽锤,西班牙語取 es,法語取 fr朦佩,自動(dòng)則取 auto
// w:查詢內(nèi)容
- 根據(jù) 金山詞霸API 的數(shù)據(jù)格式并思,創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類:
Translation.java
public class Translation {
private int status;
private content content;
private static class content {
private String from;
private String to;
private String vendor;
private String out;
private int errNo;
}
//定義 輸出返回?cái)?shù)據(jù) 的方法
public void show() {
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);
}
}
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請(qǐng)求 的接口
采用 **注解 **描述 網(wǎng)絡(luò)請(qǐng)求參數(shù)。
GetRequest_Interface.java
public interface GetRequest_Interface {
@GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
Call<Translation> getCall();
// 注解里傳入 網(wǎng)絡(luò)請(qǐng)求 的部分URL地址
// Retrofit把網(wǎng)絡(luò)請(qǐng)求的URL分成了兩部分:一部分放在Retrofit對(duì)象里语稠,另一部分放在網(wǎng)絡(luò)請(qǐng)求接口里
// 如果接口里的url是一個(gè)完整的網(wǎng)址宋彼,那么放在Retrofit對(duì)象里的URL可以忽略
// getCall()是接受網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)的方法
}
接下來的步驟均在GetRequest.java內(nèi)實(shí)現(xiàn)(看注釋)
步驟4:創(chuàng)建Retrofit對(duì)象
步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口 的實(shí)例
步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求
以最常用的 異步請(qǐng)求 為例
步驟7:處理返回?cái)?shù)據(jù)
GetRequest.java
public class GetRequest extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
request();
// 使用Retrofit封裝的方法
}
public void request() {
//步驟4:創(chuàng)建Retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/") // 設(shè)置 網(wǎng)絡(luò)請(qǐng)求 Url
.addConverterFactory(GsonConverterFactory.create()) //設(shè)置使用Gson解析(記得加入依賴)
.build();
// 步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口 的實(shí)例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//對(duì) 發(fā)送請(qǐng)求 進(jìn)行封裝
Call<Translation> call = request.getCall();
//步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步)
call.enqueue(new Callback<Translation>() {
//請(qǐng)求成功時(shí)回調(diào)
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
// 步驟7:處理返回的數(shù)據(jù)結(jié)果
response.body().show();
}
//請(qǐng)求失敗時(shí)回調(diào)
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("連接失敗");
}
});
}
}
由于此處采用了 Gson 解析,所以需要在 Gradle加入依賴
build.gradle
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
運(yùn)行結(jié)果
Demo地址
Carson_Ho的Github:https://github.com/Carson-Ho/RetrofitDemo
4.2 實(shí)例2
實(shí)現(xiàn)的功能:將 英文 翻譯成 中文
-
實(shí)現(xiàn)方法:采用
Post方法
對(duì) 有道API 發(fā)送網(wǎng)絡(luò)請(qǐng)求采用
Gson
進(jìn)行數(shù)據(jù)解析
- 使用步驟
步驟1:添加Retrofit庫的依賴
步驟2:創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請(qǐng)求 的接口
步驟4:創(chuàng)建 Retrofit 實(shí)例
步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口實(shí)例 并 配置網(wǎng)絡(luò)請(qǐng)求參數(shù)
步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(采用最常用的異步方式)
封裝了 數(shù)據(jù)轉(zhuǎn)換仙畦、線程切換的操作
**步驟7: **處理服務(wù)器返回的數(shù)據(jù)
接下來输涕,我們一步步進(jìn)行Retrofit的使用。
- 具體使用
步驟1:添加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庫
}
2. 添加 網(wǎng)絡(luò)權(quán)限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
步驟2:創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類
- API 的數(shù)據(jù)格式說明如下:
// URL
http://fanyi.youdao.com/translate
// URL實(shí)例
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:語言自動(dòng)檢測(cè)時(shí)為 null厢汹,為 null 時(shí)可為空。英譯中為 EN2ZH_CN谐宙,中譯英為 ZH_CN2EN,日譯中為 JA2ZH_CN界弧,中譯日為 ZH_CN2JA凡蜻,韓譯中為 KR2ZH_CN,中譯韓為 ZH_CN2KR垢箕,中譯法為 ZH_CN2FR划栓,法譯中為 FR2ZH_CN
// keyform:mdict. + 版本號(hào) + .手機(jī)平臺(tái)√趸瘢可為空
// model:手機(jī)型號(hào)忠荞。可為空
// mid:平臺(tái)版本∥海可為空
// imei:???堂油。可為空
// vendor:應(yīng)用下載平臺(tái)碧绞「颍可為空
// screen:屏幕寬高〖チ冢可為空
// ssid:用戶名迫靖。可為空
// abtest:???兴使∠狄耍可為空
// 請(qǐng)求方式說明
// 請(qǐng)求方式:POST
// 請(qǐng)求體:i
// 請(qǐng)求格式:x-www-form-urlencoded
- 根據(jù) 有道API 的數(shù)據(jù)格式,創(chuàng)建 接收服務(wù)器返回?cái)?shù)據(jù) 的類:
Translation.java
public class Translation1 {
private String type;
private int errorCode;
private int elapsedTime;
private List<List<TranslateResultBean>> translateResult;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getElapsedTime() {
return elapsedTime;
}
public void setElapsedTime(int elapsedTime) {
this.elapsedTime = elapsedTime;
}
public List<List<TranslateResultBean>> getTranslateResult() {
return translateResult;
}
public void setTranslateResult(List<List<TranslateResultBean>> translateResult) {
this.translateResult = translateResult;
}
public static class TranslateResultBean {
/**
* src : merry me
* tgt : 我快樂
*/
public String src;
public String tgt;
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getTgt() {
return tgt;
}
public void setTgt(String tgt) {
this.tgt = tgt;
}
}
}
步驟3:創(chuàng)建 用于描述網(wǎng)絡(luò)請(qǐng)求 的接口
采用 注解 描述 網(wǎng)絡(luò)請(qǐng)求參數(shù)发魄。
PostRequest_Interface.java
public interface PostRequest_Interface {
@POST("translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=")
@FormUrlEncoded
Call<Translation1> getCall(@Field("i") String targetSentence);
//采用@Post表示Post方法進(jìn)行請(qǐng)求(傳入部分url地址)
// 采用@FormUrlEncoded注解的原因:API規(guī)定采用請(qǐng)求格式x-www-form-urlencoded,即表單形式
// 需要配合@Field 向服務(wù)器提交需要的字段
}
接下來的步驟均在PostRequest.java內(nèi)實(shí)現(xiàn)(看注釋)
步驟4:創(chuàng)建Retrofit對(duì)象
步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口 的實(shí)例
步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求
以最常用的 異步請(qǐng)求 為例
步驟7:處理返回?cái)?shù)據(jù)
PostRequest.java
public class PostRequest extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
request();
}
public void request() {
//步驟4:創(chuàng)建Retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") // 設(shè)置 網(wǎng)絡(luò)請(qǐng)求 Url
.addConverterFactory(GsonConverterFactory.create()) //設(shè)置使用Gson解析(記得加入依賴)
.build();
// 步驟5:創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口 的實(shí)例
PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);
//對(duì) 發(fā)送請(qǐng)求 進(jìn)行封裝(設(shè)置需要翻譯的內(nèi)容)
Call<Translation1> call = request.getCall("I love you");
//步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步)
call.enqueue(new Callback<Translation1>() {
//請(qǐng)求成功時(shí)回調(diào)
@Override
public void onResponse(Call<Translation1> call, Response<Translation1> response) {
// 步驟7:處理返回的數(shù)據(jù)結(jié)果:輸出翻譯的內(nèi)容
System.out.println(response.body().getTranslateResult().get(0).get(0).getTgt());
}
//請(qǐng)求失敗時(shí)回調(diào)
@Override
public void onFailure(Call<Translation1> call, Throwable throwable) {
System.out.println("請(qǐng)求失敗");
System.out.println(throwable.getMessage());
}
});
}
}
由于此處采用了 Gson 解析盹牧,所以需要在 Gradle
加入依賴
build.gradle
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
運(yùn)行結(jié)果
Demo地址
Carson_Ho的Github:https://github.com/Carson-Ho/RetrofitDemo
5. Retrofit 的拓展使用
- Retrofit的使用場(chǎng)景非常豐富,如支持
RxJava
和Prototocobuff
- 具體設(shè)置也非常簡單 & 方便:
<-- 主要在創(chuàng)建Retrofit對(duì)象中設(shè)置 -->
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(""http://fanyi.youdao.com/"")
.addConverterFactory(ProtoConverterFactory.create()) // 支持Prototocobuff解析
.addConverterFactory(GsonConverterFactory.create()) // 支持Gson解析
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava
.build();
具體關(guān)于 RxJava
的使用這里就不展開欠母,請(qǐng)期待下篇關(guān)于 Rxjava
的文章欢策。
6. 總結(jié)
- 看完本文,相信你已經(jīng)非常熟悉
Retrofit 2.0
的使用 - 如果你希望繼續(xù)閱讀
Retrofit 2.0
的源碼赏淌,請(qǐng)看我寫的文章:Android:手把手帶你深入剖析 Retrofit 2.0 源碼 - 接下來踩寇,我將繼續(xù)分析與 Retrofit 配合使用的 RxJava,有興趣可以繼續(xù)關(guān)注Carson_Ho的安卓開發(fā)筆記