Android Retrofit 2.5.0使用基礎詳解

前言

  • 在Andrroid開發中,網絡請求必不可少
  • 而在Android全部網絡請求庫中,Retrofit是最受開發者歡迎的一個網絡請求庫

retrofit:2.5.0 官方文檔java

retrofit:2.5.0 - githubandroid

簡介

  • Retrofit是Square公司開發的一款針對Android網絡請求的框架,遵循Restful設計風格,底層基於OkHttp.

功能

  • 支持同步/異步網絡請求
  • 支持多種數據的解析&序列化格式(Gson、json、XML等等)
  • 經過註解配置網絡請求參數
  • 提供對Rxjava的支持
  • 高度解耦,使用方便

對比其餘網絡請求框架

  • 性能最好,速度最快
  • 高度封裝致使擴展性差
  • 簡潔易用,代碼簡化
  • 解耦完全,職責細分
  • 易與其餘框架聯用(Rxjava)

使用場景

  • 任何場景下建議優先使用

網絡請求流程

  • App應用程序經過 Retrofit 請求網絡,其實是使用 Retrofit 接口層封裝請求參數、Header、Url 等信息,以後由 OkHttp 完成後續的請求操做
  • 在服務端返回數據以後,OkHttp 將原始的結果交給 Retrofit,Retrofit根據用戶的需求對結果進行解析

請求流程

具體使用

1.添加Retrofit庫的依賴

dependencies {
      implementation 'com.squareup.retrofit2:retrofit:2.5.0'
     api 'com.squareup.retrofit2:converter-gson:2.0.2'
}

2. 添加 網絡權限

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

3. 建立 裝載服務器返回數據 的類

public class ResultData{
    ...
    // 根據返回數據的格式和數據解析方式(Json、XML等)定義

        }

4. 建立 用於配置網絡請求 的接口

  • Retrofit將 Http請求 抽象成 Java接口:採用 註解 描述網絡請求參數 和配置網絡請求參數
public interface GetRequestInterface {

    @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
    Call<ResultData>  getCall();
    // @GET註解的做用:採用Get方法發送網絡請求
 
    // getCall() = 接收網絡請求數據的方法
    // 其中返回類型爲Call<*>,*是接收數據的類(即上面定義的Translation類)
    // 若是想直接得到Responsebody中的內容,能夠定義網絡請求返回值爲Call<ResponseBody>
}

註解說明

  • 網絡請求方法:@GET、@POST、@PUT、@DELETE、@HEAD(經常使用)
  • 網絡請求標記: @FormUrlEncoded、@Multipart、@Streaming
  • 網絡請求參數: @Header &、@Headers、 @Body、@Field 、 @FieldMap、@Part 、 @PartMap、@Query、@QueryMap、@Path、@Url

具體做用以及解釋請自行前往官方文檔查看,這裏就不一一解釋了git

5. 建立 Retrofit 實例

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/") // 設置網絡請求的公共Url地址
                .addConverterFactory(GsonConverterFactory.create()) // 設置數據解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺
                .build();
  • 數據解析器說明
    Retrofit支持多種數據解析方式,使用時須要在Gradle添加依賴

數據解析器
Gradle依賴github

Gson
com.squareup.retrofit2:converter-gson:2.0.2json


Jacksonsegmentfault

com.squareup.retrofit2:converter-jackson:2.0.2

Simple XML
com.squareup.retrofit2:converter-simplexml:2.0.2api


Protobuf
com.squareup.retrofit2:converter-protobuf:2.0.2服務器


Moshirestful

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

  • 網絡適配器說明

Retrofit支持多種網絡請求適配器方式:guava、Java8和rxjava
Android 提供默認的 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

6.建立 網絡請求接口實例

// 建立 網絡請求接口 的實例
        GetRequestInterface request = retrofit.create(GetRequestInterface.class);

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

7. 發起網絡請求(異步 / 同步)

/發送網絡請求(異步)
        call.enqueue(new Callback<ResultData>() {
            //請求成功時回調
            @Override
            public void onResponse(Call<ResultData> call, Response<ResultData> response) {
                //處理結果
         
            }

            //請求失敗時候的回調
            @Override
            public void onFailure(Call<ResultData> call, Throwable throwable) {
             //提示失敗
            }
        });

// 發送網絡請求(同步)
Response<ResultData> response = call.execute();

8. 處理返回數據

//發送網絡請求(異步)
        call.enqueue(new Callback<ResultData>() {
            //請求成功時回調
            @Override
            public void onResponse(Call<ResultData> call, Response<ResultData> response) {
                // 對返回數據進行處理
                response.body();//拿到ResultData對象進行數據操做
            }

            //請求失敗時候的回調
            @Override
            public void onFailure(Call<ResultData> call, Throwable throwable) {
                System.out.println("鏈接失敗");
            }
        });

// 發送網絡請求(同步)
  Response<ResultData> response = call.execute();
  // 對返回數據進行處理
  response.body().blabla;

總結

  • Retrofit 是一個 restful 的 HTTP 網絡請求框架的封裝。
  • 網絡請求的工做本質上是 OkHttp 完成,而 Retrofit 僅負責 網絡請求接口的封裝
  • App應用程序經過 Retrofit 請求網絡,其實是使用 Retrofit 接口層封裝請求參數、Header、Url 等信息,以後由 OkHttp 完成後續的請求操做
  • 在服務端返回數據以後,OkHttp 將原始的結果交給 Retrofit,Retrofit根據用戶的需求對結果進行解析
  • 相對其餘開源庫而言代碼簡潔使用更加方便.
關於Retrofit 2.5的簡單介紹到這裏就結束了,感謝閱讀.

參考文章:

歡迎關注做者darryrzhong,更多幹貨等你來拿喲.

請賞個小紅心!由於你的鼓勵是我寫做的最大動力!

更多精彩文章請關注
相關文章
相關標籤/搜索