Android網路請求框架Retrofit使用介紹
前言
在android開發中,網路請求是最常用的操作之一,目前熱門的網路請求框架有:Retrofit、volley、okhttp、Android-Async-Http,這裡公司專案中用到Retrofit,之前沒了解過,這裡做個學習記錄。
本文參考博文:這是一份很詳細的 Retrofit 2.0 使用教程(含例項講解)
1.簡介
Tag:Retrofit是一個RESTful的Http請求框架的封裝,網路請求本質上是okhttp完成,Retrofit僅負責網路請求介面的封裝。
請求處理流:
App應用程式通過 Retrofit 請求網路,實際上是使用 Retrofit 介面層封裝請求引數、Header、Url 等資訊,之後由 OkHttp 完成後續的請求操作。
2.使用介紹
步驟共7步:
- 步驟1:新增依賴庫。
- 步驟2:建立接收伺服器返回資料的類。
- 步驟3:建立用於描述網路請求的介面
- 步驟4:建立Retrofit例項
- 步驟5:建立網路請求介面例項並配置網路請求引數
- 步驟6:傳送網路請求
- 步驟7:處理伺服器返回的資料
步驟1:新增依賴庫。
1.在module的build.gradle中新增對Retrofit庫的依賴
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.0.2'
// Retrofit庫
}
2.網路許可權別忘了
<uses-permission android:name="android.permission.INTERNET"/>
步驟2:建立接收伺服器返回資料的類
Reception.java
public class Reception {
...
// 根據返回資料的格式和資料解析方式(Json、XML等)定義
// 下面會在例項進行說明
}
步驟3:建立 用於描述網路請求 的介面
Retrofit將網路請求抽象成介面,採用註解描述網路請求引數和配置網路請求引數
- 用 動態代理 動態 將該介面的註解“翻譯”成一個 Http 請求,最後再執行 Http 請求
- 注:介面中的每個方法的引數都需要使用註解標註,否則會報錯
public interface ApiService {
@FormUrlEncoded
@Headers("Content-Type:application/x-www-form-urlencoded; charset=utf-8")
@POST("{uri}")
Call<Reception> post(@Path(value = "uri", encoded = true) String uri, @FieldMap Map<String, String> params);
}
註解型別:
註解說明:
網路請求方法(註解名字分別對應著網路請求的操作名):
標記:
a. @FormUrlEncoded
- 作用:表示傳送form-encoded的資料
每個鍵值對需要用@Filed來註解鍵名,隨後的物件需要提供值。
b. @Multipart
- 作用:表示傳送form-encoded的資料(適用於 有檔案 上傳的場景)
每個鍵值對需要用@Part來註解鍵名,隨後的物件需要提供值。
public interface GetRequest_Interface {
/**
*表明是一個表單格式的請求(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} 中已經包含了表單欄位的資訊),
*/
@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);
網路請求引數
a. @Header & @Headers
- 作用:新增請求頭 &新增不固定的請求頭
- 具體使用如下:
// @Header
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
// @Headers
@Headers("Authorization: authorization")
@GET("user")
Call<User> getUser()
// 以上的效果是一致的。
// 區別在於使用場景和使用方式
// 1. 使用場景:@Header用於新增不固定的請求頭,@Headers用於新增固定的請求頭
// 2. 使用方式:@Header作用於方法的引數;@Headers作用於方法
- b. @Body
- 作用:以
Post
方式 傳遞 自定義資料型別 給伺服器 - 特別注意:如果提交的是一個Map,那麼作用相當於
@Field
不過Map要經過
FormBody.Builder
類處理成為符合 Okhttp 格式的表單,如:
FormBody.Builder builder = new FormBody.Builder();
builder.add("key","value");
c. @Field & @FieldMap
- 作用:傳送 Post請求 時提交請求的表單欄位
- 具體使用:與
@FormUrlEncoded
註解配合使用
d. @Part & @PartMap
-
作用:傳送 Post請求 時提交請求的表單欄位
與@Field的區別:功能相同,但攜帶的引數型別更加豐富,包括資料流,所以適用於 有檔案上傳 的場景
-
具體使用:與
@Multipart
註解配合使用
public interface GetRequest_Interface {
/**
* {@link Part} 後面支援三種類型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意型別
* 除 {@link okhttp3.MultipartBody.Part} 以外,其它型別都必須帶上表單欄位({@link okhttp3.MultipartBody.Part} 中已經包含了表單欄位的資訊),
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
/**
* PartMap 註解支援一個Map作為引數,支援 {@link RequestBody } 型別,
* 如果有其它的型別,會被{@link retrofit2.Converter}轉換,如後面會介紹的 使用{@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"), "這裡是模擬檔案的內容");
// @Part
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
ResponseBodyPrinter.printResponseBody(call3);
// @PartMap
// 實現和上面同樣的效果
Map<String, RequestBody> fileUpload2Args = new HashMap<>();
fileUpload2Args.put("name", name);
fileUpload2Args.put("age", age);
//這裡並不會被當成檔案,因為沒有檔名(包含在Content-Disposition請求頭中),但上面的 filePart 有
//fileUpload2Args.put("file", file);
Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //單獨處理檔案
ResponseBodyPrinter.printResponseBody(call4);
}
e. @Query和@QueryMap
-
作用:用於
@GET
方法的查詢引數(Query = Url 中 ‘?’ 後面的 key-value)如:url = http://www.println.net/?cate=android,其中,Query = cate
-
具體使用:配置時只需要在介面方法中增加一個引數即可:
@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
// 在發起請求時, {user} 會被替換為方法的第一個引數 user(被@Path註解作用)
}
g. @Url
- 作用:直接傳入一個請求的 URL變數 用於URL設定
- 具體使用:
public interface GetRequest_Interface {
@GET
Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
// 當有URL註解時,@GET傳入的URL就可以省略
// 當GET、POST...HTTP等方法中沒有設定Url時,則必須使用 {@link Url}提供
}
步驟4:建立 Retrofit 例項
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") // 設定網路請求的Url地址
.addConverterFactory(GsonConverterFactory.create()) // 設定資料解析器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支援RxJava平臺
.build();
URL說明:
Retrofit把 網路請求的URL 分成了兩部分設定:
- 網路請求的完整 Url =在建立Retrofit例項時通過.baseUrl()設定 +網路請求介面的註解設定(
@POST("{uri}") Call<Reception> post(@Path(value = "uri", encoded = true) String uri, @FieldMap Map<String, String> params); )
a.資料解析器(Converter):
- Retrofit支援多種資料解析方式
- 使用時需要在Gradle新增依賴
資料解析器 | 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. 關於網路請求介面卡(CallAdapter)
- Retrofit支援多種網路請求介面卡方式:guava、Java8和rxjava
使用時如使用的是
Android
預設的CallAdapter
,則不需要新增網路請求介面卡的依賴,否則則需要按照需求進行新增
Retrofit 提供的CallAdapter
- 使用時需要在Gradle新增依賴:
網路請求介面卡 | 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:建立網路請求介面例項
// 建立 網路請求介面 的例項
ApiService apiService= retrofit.create(ApiService.class);
//對 傳送請求 進行封裝
Call<Reception> call = apiService.post("appApi",param);
步驟6:傳送網路請求(非同步 / 同步)
//傳送網路請求(非同步)
call.enqueue(new Callback<Reception>() {
//請求成功時回撥
@Override
public void onResponse(Call<Reception> call, Response<Reception> response) {
//請求處理,輸出結果
response.body().show();
}
//請求失敗時候的回撥
@Override
public void onFailure(Call<Reception> call, Throwable throwable) {
System.out.println("連線失敗");
}
});
// 傳送網路請求(同步)
Response<Reception> response = call.execute();
步驟7:處理返回資料
通過response
類的 body()
對返回的資料進行處理
//傳送網路請求(非同步)
call.enqueue(new Callback<Translation>() {
//請求成功時回撥
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
// 對返回資料進行處理
//Translation translation= response.body();
response.body().show();
}
//請求失敗時候的回撥
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("連線失敗");
}
});
// 傳送網路請求(同步)
Response<Reception> response = call.execute();
// 對返回資料進行處理
response.body().show();
Retrofit總體使用步驟就是以上七步。
同時Retrofit可以配合RxJava使用,這裡繼續學習RxJava。