1. 程式人生 > >Android Retrofit 2.0 的詳細使用

Android Retrofit 2.0 的詳細使用

前言

  • Andrroid開發中,網路請求十分常用
  • 而在Android網路請求庫中,Retrofit是當下最熱的一個網路請求庫
Github截圖
  • 今天,我將獻上一份非常詳細Retrofit v2.0的使用教程,希望你們會喜歡。

目錄

目錄

1. 簡介

示意圖

特別注意:

  • 準確來說,Retrofit 是一個 RESTful 的 HTTP 網路請求框架的封裝。
  • 原因:網路請求的工作本質上是 OkHttp 完成,而 Retrofit 僅負責 網路請求介面的封裝
本質過程
  • App應用程式通過 Retrofit 請求網路,實際上是使用 Retrofit 介面層封裝請求引數、Header、Url 等資訊,之後由 OkHttp 完成後續的請求操作
  • 在服務端返回資料之後,OkHttp 將原始的結果交給 Retrofit,Retrofit根據使用者的需求對結果進行解析

2. 與其他開源請求庫對比

除了Retrofit,如今Android中主流的網路請求框架有:

  • Android-Async-Http
  • Volley
  • OkHttp

下面是簡單介紹:

網路請求載入 - 介紹

一圖讓你瞭解全部的網路請求庫和他們之間的區別!

網路請求庫 - 對比

附:各個主流網路請求庫的Github地址

3. 使用介紹

使用 Retrofit 的步驟共有7個:

步驟1:新增Retrofit庫的依賴
步驟2:建立 接收伺服器返回資料 的類
步驟3:建立 用於描述網路請求 的介面
步驟4:建立 Retrofit 例項
步驟5:

建立 網路請求介面例項 並 配置網路請求引數
步驟6:傳送網路請求(非同步 / 同步)

封裝了 資料轉換、執行緒切換的操作

**步驟7: **處理伺服器返回的資料

接下來,我們一步步進行講解。

步驟1:新增Retrofit庫的依賴

1. 在 Gradle加入Retrofit庫的依賴

build.gradle

dependencies {
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    // Retrofit庫
  }

2. 新增 網路許可權
AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"
/>

步驟2:建立 接收伺服器返回資料 的類

Reception.java

public class Reception {
    ...
    // 根據返回資料的格式和資料解析方式(Json、XML等)定義
    // 下面會在例項進行說明
        }

步驟3:建立 用於描述網路請求 的介面

  • Retrofit將 Http請求 抽象成 Java介面:採用 註解 描述網路請求引數 和配置網路請求引數
  1. 用 動態代理 動態 將該介面的註解“翻譯”成一個 Http 請求,最後再執行 Http 請求
  2. 注:介面中的每個方法的引數都需要使用註解標註,否則會報錯

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方法傳送網路請求

    // getCall() = 接收網路請求資料的方法
    // 其中返回型別為Call<*>,*是接收資料的類(即上面定義的Translation類)
    // 如果想直接獲得Responsebody中的內容,可以定義網路請求返回值為Call<ResponseBody>
}

下面詳細介紹Retrofit 網路請求介面 的註解型別。

註解型別

註解型別

註解說明

第一類:網路請求方法

網路請求方法註解

詳細說明:
a. @GET、@POST、@PUT、@DELETE、@HEAD
以上方法分別對應 HTTP中的網路請求方式

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方法傳送網路請求
    // getCall() = 接收網路請求資料的方法
    // 其中返回型別為Call<*>,*是接收資料的類(即上面定義的Translation類)
}

此處特意說明URL的組成:Retrofit把 網路請求的URL 分成了兩部分設定:

// 第1部分:在網路請求介面的註解設定
 @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation>  getCall();

// 第2部分:在建立Retrofit例項時通過.baseUrl()設定
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/") //設定網路請求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //設定資料解析器
                .build();

// 從上面看出:一個請求的URL可以通過 替換塊 和 請求方法的引數 來進行動態的URL更新。
// 替換塊是由 被{}包裹起來的字串構成
// 即:Retrofit支援動態改變網路請求根目錄
  • 網路請求的完整 Url =在建立Retrofit例項時通過.baseUrl()設定 +網路請求介面的註解設定(下面稱 “path“ )
  • 具體整合的規則如下:
URL整合規則

建議採用第三種方式來配置,並儘量使用同一種路徑形式。

b. @HTTP

  • 作用:替換@GET、@POST、@PUT、@DELETE、@HEAD註解的作用 及 更多功能拓展
  • 具體使用:通過屬性method、path、hasBody進行設定
public interface GetRequest_Interface {
    /**
     * method:網路請求的方法(區分大小寫)
     * path:網路請求地址路徑
     * hasBody:是否有請求體
     */
    @HTTP(method = "GET", path = "blog/{id}", hasBody = false)
    Call<ResponseBody> getCall(@Path("id") int id);
    // {id} 表示是一個變數
    // method 的值 retrofit 不會做處理,所以要自行保證準確
}

第二類:標記

標記類註解

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")
        @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 註解配合使用
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);

/**
         * Map的key作為表單的鍵
         */
        @POST("/form")
        @FormUrlEncoded
        Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);

}

// 具體使用
         // @Field
        Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);

        // @FieldMap
        // 實現的效果與上面相同,但要傳入Map
        Map<String, Object> map = new HashMap<>();
        map.put("username", "Carson");
        map.put("age", 24);
        Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);

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)
  • 具體使用:配置時只需要在介面方法中增加一個引數即可:
   @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();

a. 關於資料解析器(Converter)

  • 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

b. 關於網路請求介面卡(CallAdapter)

  • 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

步驟5:建立 網路請求介面例項

        // 建立 網路請求介面 的例項
        GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);

        //對 傳送請求 進行封裝
        Call<Reception> call = request.getCall();

步驟6:傳送網路請求(非同步 / 同步)

封裝了 資料轉換、執行緒切換的操作

//傳送網路請求(非同步)
        call.enqueue(new Callback<Translation>() {
            //請求成功時回撥
            @Override
            public void onResponse(Call<Translation> call, Response<Translation> response) {
                //請求處理,輸出結果
                response.body().show();
            }

            //請求失敗時候的回撥
            @Override
            public void onFailure(Call<Translation> 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) {
                // 對返回資料進行處理
                response.body().show();
            }

            //請求失敗時候的回撥
            @Override
            public void onFailure(Call<Translation> call, Throwable throwable) {
                System.out.println("連線失敗");
            }
        });

// 傳送網路請求(同步)
  Response<Reception> response = call.execute();
  // 對返回資料進行處理
  response.body().show();

4. 例項講解

接下來,我將用兩個例項分別對 Retrofit GET方式 和 POST方式進行 網路請求 講解。

4.1 例項1

  • 實現功能:將中文翻譯成英文
  • 實現方案:採用Get方法對 金山詞霸API 傳送網路請求

採用 

相關推薦

no