簡(jiǎn)介
Retrofit:一個(gè)RESTful的Http請(qǐng)求框架(基于OKhttp)
特別注意:
準(zhǔn)確來(lái)說(shuō),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)用程序通過(guò) 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)行解析
使用介紹
使用Retrofit的步驟如下:
1.添加Retrofit庫(kù)的依賴
2.創(chuàng)建實(shí)體類(根據(jù)服務(wù)器返回?cái)?shù)據(jù)生成對(duì)應(yīng)的實(shí)體類)
3.創(chuàng)建用于描述網(wǎng)絡(luò)請(qǐng)求的接口(接口里可有多個(gè)方法)
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)求(同步/異步)
7.處理服務(wù)器返回的數(shù)據(jù)
步驟1:添加Retrofit庫(kù)的依賴
1.添加依賴
build.gradle
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.0.2'
// Retrofit庫(kù)
compile 'com.squareup.okhttp3:okhttp:3.1.2'
// Okhttp庫(kù)
compile 'com.squareup.retrofit2:converter-gson:2.0.2'//如果需要使用GSON解析
}
2.添加網(wǎng)絡(luò)權(quán)限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
步驟2:創(chuàng)建實(shí)體類(根據(jù)服務(wù)器返回?cái)?shù)據(jù)生成對(duì)應(yīng)的實(shí)體類)
Reception.java
public class Reception {
...
// 根據(jù)返回?cái)?shù)據(jù)的格式和數(shù)據(jù)解析方式(Json、XML等)定義
// 下面會(huì)在實(shí)例進(jìn)行說(shuō)明
}
步驟3:創(chuàng)建用于描述網(wǎng)絡(luò)請(qǐng)求的接口(接口里可有多個(gè)方法)
- Retrofit將 Http請(qǐng)求 抽象成 Java接口:采用 注解 描述 網(wǎng)絡(luò)請(qǐng)求參數(shù) 和配置網(wǎng)絡(luò)請(qǐng)求參數(shù)
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)求接口 的注解類型:
注解類型

注解說(shuō)明
第一類:網(wǎng)絡(luò)請(qǐng)求方法

注解說(shuō)明
參考文章:https://blog.csdn.net/carson_ho/article/details/73732076
第二類:標(biāo)記

a.
@FormUrlEncoded
作用:表示發(fā)送form-encoded的數(shù)據(jù)
注意:每個(gè)鍵值對(duì)需要用@Filed來(lái)注解鍵名,隨后的對(duì)象需要提供值。
b.
@Multipart
作用:表示發(fā)送form-encoded的數(shù)據(jù)(適用于 有文件 上傳的場(chǎng)景)
注意:每個(gè)鍵值對(duì)需要用@Part來(lái)注解鍵名,隨后的對(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
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)容");
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
第三類:網(wǎng)絡(luò)請(qǐng)求參數(shù)

這里著重講一下@File&@FileMap, @Part&@PartMap ,@Query&@QuertMap(這幾個(gè)比較常用,其它的參考文章https://blog.csdn.net/carson_ho/article/details/73732076)
@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);
@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)闆](méi)有文件名(包含在Content-Disposition請(qǐng)求頭中),但上面的 filePart 有
//fileUpload2Args.put("file", file);
Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //單獨(dú)處理文件
ResponseBodyPrinter.printResponseBody(call4);
}
@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);
步驟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)
數(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添加依賴:
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ù)
通過(guò)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();
Retrofit 的拓展使用
Retrofit的使用場(chǎng)景非常豐富,如支持RxJava和Prototocobuff
具體設(shè)置也非常簡(jiǎn)單 & 方便:
<-- 主要在創(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();
ending~下班了
備注:本文參考文章:https://blog.csdn.net/carson_ho/article/details/73732076