Retrofit-开始并创建一个Android客户端

写在开始

因为项目的需要使用到Retrofit,查阅了一些资料后,发现了这个Retrofit使用系列,讲解的十分详细,因为原版是英文的,所以准备翻译成中文的供各位一起交流学习,由于笔者英文水平也就是一般,有些词不达意的地方,烦请谅解,另外,考虑的翻译的“信、达、雅”,可能会有一些句式上的变动。在每章的开始都会给出原版地址,有兴趣的可以直接观看原版。

原文地址

Retrofit — Getting Started and Create an Android Client

什么是Retrofit

官方的主页上描述Retorfit称之为

A type-safe REST client for Android and Java.

你将会使用注解来表示HTTP请求并且默认支持URL参数替换和查询参数。另外,它提供了对于多请求body和文件上传的功能。

怎样声明一个(API)请求

请访问并阅读Retrofit homepage中API声明部分,了解怎么声明一个request,你会发现所有的重要信息通过代码的实例来清晰的表达。

准备你的Android项目

现在让我们重新把手放到键盘上,如果你已经创建了Android项目,直接开始下一段,不然我们先在IDE上建立一个项目,我们推荐使用Gradle来作为构建工具,当然用Maven也是一样的。

定义依赖:Gradle或Maven

现在我们让你的项目依赖Retrofit,选择你的构建系统然后定义Retrofit在你的pom.xml或者Gradle,当使用命令行来build项目时,构建系统会下载并提供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作为网络层,并建立在之上,你不需要明确的定义OkHttp依赖你的项目,除非你需要一个特别的版本。
现在你的项目已经准备好集成Retrofit,我们可以创建一个持续的Android API/HTTP客户端。

持续性的Android客户端

在对已有的Retrofit研究时,Bart Kiers的sample repository出来了,其实,这是一个OAuth认证的例子,但是,它提供了一个可持续发展的Android客户端的所有必要的基础,这就是为什么我们使用它来作为一个稳定的基础,并且在后面的博客中进行功能的扩展。
下面的类定义了我们客户端的基础:ServiceGenerator

Service Generator

这个 Service Generator 是我们API/HTTP的核心。在当前状态下,它只定义了一个方法去创建一个基本的对于给定的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来根据一个给定的base url创建一个REST client。举个例子,Github的API base url就是 https://api.github.com/

serviceClass 定义了一个API请求注解类或接口。以下的部分展示了具体的Retrofit的使用,以及如何定义一个示范的client。

Json映射

Retrofit 1.9默认附带google的GSON解析,你需要定义一个返回对象的类然后这个返回会自动映射,当使用Retrofit 2,你需要添加一个明确的映射转换给Retrofit,在上面,我们已经在 build.gradle 中引入了GSON的转换器

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

现在你需要添加一个转换器给Retrofit对象,需要调用 .addConverterFactory(GsonConverterFactory.create()) 在Builder中将GSON作为默认的转换器。

译者注: 除了gson之外 一般使用fastjson的用户也是有对应的转换器 需要导入 compile 'org.ligboy.retrofit2:converter-fastjson-android:2.1.0'

使用Retrofit

好,我们开始面对这个例子并且定义一个RSET client来从github上请求数据,首先,我们先得创建一个interface并且定义需要的方法

GitHub Client

下面的代码定义了一个GithubClient和一个方法来请求一个contributors的列表,这也示例了参数的替换功能(这个owner和repo参数会被请求时的参数所替代)

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 这个类的组成需要属性去映射返回的数据

static class Contributor {  
    String login;
    int contributions;
}

至于先前提到的JSON映射,GithubClient定义了一个 contributors 方法返回了一个List<Contributor>,只要匹配到给定的类,Retrofit能确保服务端的返回会映射成功。

API 请求示例

下面的代码片段示例了 ServiceGenerator 的使用来实例化具体的GithubClient,并且通过方法调用来获取contributors ,这个片段是改进过的示例代码
你需要手动给 ServiceGenerator 定义一个base url "https://api.github.com/" ,另外还要创建一个 createService 来接收两个参数: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 + ")");
    }
}
引用文章
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容