Retrofit-開始并創(chuàng)建一個Android客戶端

寫在開始

因為項目的需要使用到Retrofit,查閱了一些資料后,發(fā)現(xiàn)了這個Retrofit使用系列,講解的十分詳細,因為原版是英文的,所以準備翻譯成中文的供各位一起交流學習,由于筆者英文水平也就是一般,有些詞不達意的地方,煩請諒解,另外,考慮的翻譯的“信、達、雅”,可能會有一些句式上的變動。在每章的開始都會給出原版地址,有興趣的可以直接觀看原版。

原文地址

Retrofit — Getting Started and Create an Android Client

什么是Retrofit

官方的主頁上描述Retorfit稱之為

A type-safe REST client for Android and Java.

你將會使用注解來表示HTTP請求并且默認支持URL參數(shù)替換和查詢參數(shù)。另外,它提供了對于多請求body和文件上傳的功能。

怎樣聲明一個(API)請求

請訪問并閱讀Retrofit homepage中API聲明部分,了解怎么聲明一個request,你會發(fā)現(xiàn)所有的重要信息通過代碼的實例來清晰的表達。

準備你的Android項目

現(xiàn)在讓我們重新把手放到鍵盤上,如果你已經(jīng)創(chuàng)建了Android項目,直接開始下一段,不然我們先在IDE上建立一個項目,我們推薦使用Gradle來作為構建工具,當然用Maven也是一樣的。

定義依賴:Gradle或Maven

現(xiàn)在我們讓你的項目依賴Retrofit,選擇你的構建系統(tǒng)然后定義Retrofit在你的pom.xml或者Gradle,當使用命令行來build項目時,構建系統(tǒng)會下載并提供library給你的項目,我們提議在使用Retrofit時配合OkHttp同時也需要依賴 Okio。

Retrofit 1.9
pom.xml
<dependency> 
  <groupId>com.squareup.retrofit</groupId>
  <artifactId>retrofit</artifactId>
  <version>1.9.0</version>
</dependency>
<dependency> 
  <groupId>com.squareup.okhttp</groupId>
  <artifactId>okhttp</artifactId> 
  <version>2.7.2</version>
</dependency> 
build.gradle
dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.7.2'
}
Retrofit 2

使用下面的依賴如果你使用的是Retrofit2版本

pom.xml
<dependency> 
  <groupId>com.squareup.retrofit2</groupId> 
  <artifactId>retrofit</artifactId> 
  <version>2.1.0</version>
</dependency> 
<dependency> 
  <groupId>com.squareup.retrofit2</groupId> 
  <artifactId>converter-gson</artifactId> 
  <version>2.1.0</version>
</dependency>
build.gradle
dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}

Retrofit2默認情況下利用OkHttp作為網(wǎng)絡層,并建立在之上,你不需要明確的定義OkHttp依賴你的項目,除非你需要一個特別的版本。
現(xiàn)在你的項目已經(jīng)準備好集成Retrofit,我們可以創(chuàng)建一個持續(xù)的Android API/HTTP客戶端。

持續(xù)性的Android客戶端

在對已有的Retrofit研究時,Bart Kiers的sample repository出來了,其實,這是一個OAuth認證的例子,但是,它提供了一個可持續(xù)發(fā)展的Android客戶端的所有必要的基礎,這就是為什么我們使用它來作為一個穩(wěn)定的基礎,并且在后面的博客中進行功能的擴展。
下面的類定義了我們客戶端的基礎:ServiceGenerator

Service Generator

這個 Service Generator 是我們API/HTTP的核心。在當前狀態(tài)下,它只定義了一個方法去創(chuàng)建一個基本的對于給定的class/interface的REST類型的適配器,下面是代碼示例

Retrofit 1.9
public class ServiceGenerator {

    public static final String API_BASE_URL = "http://your.api-base.url";

    private static RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(API_BASE_URL)
                .setClient(new OkClient(new OkHttpClient()));

    public static <S> S createService(Class<S> serviceClass) {
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }
}
Retrofit 2
public class ServiceGenerator {

    public static final String API_BASE_URL = "http://your.api-base.url";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}

這個 ServiceGenerator 類使用Retrofit的 RestAdapter -Builder來根據(jù)一個給定的base url創(chuàng)建一個REST client。舉個例子,Github的API base url就是 https://api.github.com/

serviceClass 定義了一個API請求注解類或接口。以下的部分展示了具體的Retrofit的使用,以及如何定義一個示范的client。

Json映射

Retrofit 1.9默認附帶google的GSON解析,你需要定義一個返回對象的類然后這個返回會自動映射,當使用Retrofit 2,你需要添加一個明確的映射轉(zhuǎn)換給Retrofit,在上面,我們已經(jīng)在 build.gradle 中引入了GSON的轉(zhuǎn)換器

compile 'com.squareup.retrofit2:converter-gson:2.1.0' 

現(xiàn)在你需要添加一個轉(zhuǎn)換器給Retrofit對象,需要調(diào)用 .addConverterFactory(GsonConverterFactory.create()) 在Builder中將GSON作為默認的轉(zhuǎn)換器。

譯者注: 除了gson之外 一般使用fastjson的用戶也是有對應的轉(zhuǎn)換器 需要導入 compile 'org.ligboy.retrofit2:converter-fastjson-android:2.1.0'

使用Retrofit

好,我們開始面對這個例子并且定義一個RSET client來從github上請求數(shù)據(jù),首先,我們先得創(chuàng)建一個interface并且定義需要的方法

GitHub Client

下面的代碼定義了一個GithubClient和一個方法來請求一個contributors的列表,這也示例了參數(shù)的替換功能(這個owner和repo參數(shù)會被請求時的參數(shù)所替代)

Retrofit 1.9
public interface GitHubClient {  
    @GET("/repos/{owner}/{repo}/contributors")
    List<Contributor> contributors(
        @Path("owner") String owner,
        @Path("repo") String repo
    );
}
Retrofit 2
public interface GitHubClient {  
    @GET("/repos/{owner}/{repo}/contributors")
    Call<List<Contributor>> contributors(
        @Path("owner") String owner,
        @Path("repo") String repo
    );
}

下面定義了一個class Contributor 這個類的組成需要屬性去映射返回的數(shù)據(jù)

static class Contributor {  
    String login;
    int contributions;
}

至于先前提到的JSON映射,GithubClient定義了一個 contributors 方法返回了一個List<Contributor>,只要匹配到給定的類,Retrofit能確保服務端的返回會映射成功。

API 請求示例

下面的代碼片段示例了 ServiceGenerator 的使用來實例化具體的GithubClient,并且通過方法調(diào)用來獲取contributors ,這個片段是改進過的示例代碼
你需要手動給 ServiceGenerator 定義一個base url "https://api.github.com/" ,另外還要創(chuàng)建一個 createService 來接收兩個參數(shù):client class 和 base url。

Retrofit 1.9
public static void main(String... args) {  
    // Create a very simple REST adapter which points the GitHub API endpoint.
    GitHubClient client = ServiceGenerator.createService(GitHubClient.class);

    // Fetch and print a list of the contributors to this library.
    List<Contributor> contributors =
        client.contributors("fs_opensource", "android-boilerplate");

    for (Contributor contributor : contributors) {
        System.out.println(
                contributor.login + " (" + contributor.contributions + ")");
    }
}
Retrofit 2
public static void main(String... args) {  
    // Create a very simple REST adapter which points the GitHub API endpoint.
    GitHubClient client = ServiceGenerator.createService(GitHubClient.class);

    // Fetch and print a list of the contributors to this library.
    Call<List<Contributor>> call =
        client.contributors("fs_opensource", "android-boilerplate");

    try {
        List<Contributor> contributors = call.execute().body();
    } catch (IOException e) {
        // handle errors
    }

    for (Contributor contributor : contributors) {
        System.out.println(
                contributor.login + " (" + contributor.contributions + ")");
    }
}
引用文章
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容