原文链接:https://futurestud.io/blog/retrofit-getting-started-and-android-client
本文是Retrofit系列文章的第一篇。本系列深入挖掘几个使用案例并讨论了Retrofit的功能和扩展性。

Retrofit 系列目录

  1. 开始创建android客户端
  2. Android上的基本认证[已翻译]
  3. Android上的令牌认证[已翻译]
  4. Android上的OAuth
  5. 多个 Query 参数使用同一名字[已翻译]
  6. 同步与异步请求[已翻译]
  7. 在请求体里发送对象[已翻译]
  8. 自定义一个响应转换器[已翻译]
  9. 添加自定义请求头
  10. 可选的 Query 参数
  11. 如何集成 XML 转换器
  12. 使用 Log Level 调试请求
  13. 如何上传文件
  14. Series Round-Up
  15. Retrofit 2 — 1.9 升级指南
  16. Retrofit 2 — 如何上传文件
  17. Retrofit 2 — Log 请求与响应
  18. Retrofit 2 — Android 上的 Hawk 认证
  19. Retrofit 2 — 简单错误处理
  20. 如何在 Retrofit 1 里使用 OkHttp 3
  21. Retrofit 2 — 图书更新发布庆典
  22. 提交表单数据 — Urlencoded
  23. 提交表单数据 — Urlencoded 使用FieldMap
  24. Retrofit 2 — 在 OkHttp 拦截器里管理请求头部
  25. Retrofit 2 — 如何给每一个请求添加 Query 参数
  26. Retrofit 2 — 使用QueryMap 添加多个 Query 参数
  27. Retrofit 2 — 如何在请求时使用动态 Url
  28. Retrofit 2 — Url 处理,分辨和解析
  29. Retrofit 2 — POST 和PUT 请求里的常量, 默认值和逻辑值
  30. Retrofit 2 — 如何下载文件
  31. Retrofit 2 — 取消请求
  32. Retrofit 2 — 重用分析请求
  33. Retrofit 2 — 如何在运行时修改 API Base Url
  34. 可选Path参数
  35. 如何刷新 Access Token
  36. Retrofit 2 — 如何提交文本请求体
  37. Retrofit 2 — 使用 Query 参数来分页
  38. Retrofit 2 — 使用 链接头和动态 Url 来分页(比如GitHub)
  39. Retrofit 2 — 使用范围头字段来分页 (比如 Heroku)
  40. Retrofit 2 — 转换器介绍
  41. Retrofit 2 — 添加并自定义 Gson 转换器
  42. Retrofit 2 — 实现自定义转换器
  43. Retrofit 2 — 只在开发环境里启用日志
  44. Retrofit 2 — 如何上传多个文件
  45. Retrofit 2 — Passing Multiple Parts Along a File with @PartMap
  46. Retrofit 2 — 模仿服务端响应基本概念
  47. Retrofit 2 — 模仿服务端响应自定义网络行为
  48. Retrofit 2 — 使用 @HeaderMap 定义动态请求头

在本篇博客里我们将浏览 Retrofit 的基本概念,并创建 android 客户端用来做 HTTP 请求.
但是请记住我们不会介绍过多入门知识和 Retrofit 是什么. 想知道更多请访问官网.

Retrofit 是什么

官网介绍如下:

A type-safe REST client for Android and Java.
(目前已改为A type-safe **HTTP client **for Android and Java,译者注)

你将使用注解来描述 HTTP 请求, URL 参数替换, 默认集成query 参数支持. 除此而外, 它还提供Multipart请求和文件上传的功能.

如何声明 (API) 请求

请访问 Retrofit 主页并阅读 API 声明部分来理解并找到如何做请求的感觉 . 在此你将发现所有重要信息,它们在代码示例里被清晰的描述.

准备你的 Android 项目

现在让我们把手放到键盘上。如果已经创建过了Android项目,那么请继续阅读下一章节。否则,请使用你最喜欢的IDE创建一个新项目。我们倾向于使用 Gradle 做为构建系统,不过当然你也可以继续使用 Maven。

定义依赖: Gradle 或者 Maven

现在让我们将 Retrofit 设为项目的一个依赖. 选择你使用的构建系统并在 pom.xml 或者build.gradle里定义 Refrofit 和它的依赖. 当执行构建命令代码时, 构建系统将会下载并提供你项目的库. 我们建议使用 Retrofit 联合 OkHTTP, 它需要 Okio 做为依赖.

Retrofit 1.9

pom.xml

      com.squareup.retrofit    retrofit    1.9.0        com.squareup.okhttp    okhttp    2.7.2

build.gradle

dependencies {      // Retrofit & OkHttp    compile 'com.squareup.retrofit:retrofit:1.9.0'    compile 'com.squareup.okhttp:okhttp:2.7.2'}

Retrofit 2

如果你使用的 Retrofit 版本2 ,请使用如下依赖:
pom.xml

      com.squareup.retrofit2    retrofit    2.1.0        com.squareup.retrofit2    converter-gson    2.1.0

build.gradle

dependencies {      // Retrofit & OkHttp    compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'}

Retrofit 2 默认情况下利用OkHttp作为网络层,是构建在它之上. 你不必显式定义 OkHttp 作为你项目的依赖, 除非你需要它的特定版本.

既然你的项目已经准备好集成 Retrofit, 那么让我们创建一个持久的 Android API/HTTP 客户端.

可持续Android客户端

在研究目前已有的 Retrofit 客户端过程中, 出现了 Bart Kiers 的例子库. 实际上他是关于用 Retrofit OAuth 认证的例子. 无论如何,它提供了一个可持续发展的Andr​​oid客户端所有必要的基础知识. 这就是为什么我们把它作为一个稳定的基础,并在未来的博客中做进一步的认证功能扩展.
接下来的类定义了我们android客户端的基础: ServiceGenerator.

Service Generator

ServiceGenerator 是我们 API/HTTP 客户端的核心. 当前, 它只定义了一个方法, 就是给已有的类/接口创建基本的 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 createService(Class 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 createService(Class serviceClass) {        Retrofit retrofit = builder.client(httpClient.build()).build();        return retrofit.create(serviceClass);    }}

ServiceGenerator 类使用 Retrofit 的 RestAdapter-Builder 结合提供的 API_BASE_URL来创建一个新的 REST 客户端. 比如, GitHub 的 API_BASE_URLhttps://api.github.com/. serviceClass 定义API请求注解类或接口. 下面的章节将显示 Retrofit 的具体使用和如何定义一个示范客户端.

JSON 映射

Retrofit 1.9 默认附带 Google的 GSON 库. 你需要做的就是定义你响应对象的类, 然后响应将被自动映射.

然而到了 Retrofit 2, 你需要显示添加一个转换器到 Retrofit 对象上. 前面,我们已经添加下列行到 build.gradle 文件来导入 Retrofit 2的 GSON 转换器.

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

现在你需要给你的 Retrofit 对象添加转换. 在Retrofit 的 builder 调用 .addConverterFactory(GsonConverterFactory.create()) 来集成 GSON 作为默认的 JSON 转换器.

Retrofit 实例

好吧,让我们面对一个例子,定义一个从GitHub请求数据的REST客户端. 首先, 我们必须创建接口并定义需要的方法.

GitHub 客户端

下面的代码定义了 GitHubClient接口, 接口定义了一个请求存储库贡献者列表的方法. 这也显示了 Retrofit 的参数替换功能的使用 (路径中的{owner} 和{repo} 在调用对象方法时将会被给定的变量替换).

Retrofit 1.9

public interface GitHubClient {      @GET("/repos/{owner}/{repo}/contributors")    List contributors(        @Path("owner") String owner,        @Path("repo") String repo    );}

Retrofit 2

public interface GitHubClient {      @GET("/repos/{owner}/{repo}/contributors")    Call> contributors(        @Path("owner") String owner,        @Path("repo") String repo    );}

这是定义的 Contributor 类. 这个类包含所需的类属性来映射响应数据.

static class Contributor {      String login;    int contributions;}

至于先前提到的JSON映射:GitHubClient 定义了返回类型为 List的方法 contributors . Retrofit 确保服务器的响应被正确的映射(响应匹配给定的类).

API 请求示例

下面的片段显示了 ServiceGenerator 的用法, 实例化客户端(具体来说是GitHub 客户端), 和用创建的 client 得到贡献者的方法调用. 这个片段是所提供的 Retrofit github客户端示例的修改后版本.
当执行GitHub 示例时, 你需要在ServiceGenerator接口手动定义基本url为 "https://api.github.com/". 另一种方法是再创建一个 createService()
方法, 接受两个参数: client 类和基本 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 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> call =        client.contributors("fs_opensource", "android-boilerplate");    try {        List contributors = call.execute().body();    } catch (IOException e) {        // handle errors    }    for (Contributor contributor : contributors) {        System.out.println(                contributor.login + " (" + contributor.contributions + ")");    }}

接下来做什么

接下来的章节介绍了如何使用 Retrofit 完成基本身份认证. 我们将展示代码例子使用用户名/电子邮件和密码来验证web服务或api. 此外,以后的文章将涵盖令牌(其中包括OAuth)API认证.
我们希望你喜欢这个概述,以及如何使用 Retrofit 完成你的第一个请求:)

附加资源

  • Retrofit 项目主页
  • Retrofit API 声明文档
  • Retrofit 基于的 认证库 作者 Bart Kiers
  • Retrofit 示例

更多相关文章

  1. Android中RelativeLayout布局各个xml相对布局属性的介绍和使用
  2. 在Android程序中使用全局变量
  3. Android(安卓)Scripting Environment -ASE
  4. Android(安卓)如何使用GPU硬件加速
  5. Android基础入门教程——1.2.2 使用Android(安卓)Studio开发Andr
  6. Android解析服务器端发来的xml数据
  7. Android中attrs.xml文件的使用详解
  8. android app 启动会白屏的解决办法
  9. 安卓selector使用方法

随机推荐

  1. 解密ThreadLocal
  2. JS内存泄漏排查方法
  3. 函数和递归
  4. 视频演示:好家伙,我直接好家伙!
  5. 深入React
  6. 今晚,我等你 ~
  7. 分布式系统的事务处理
  8. 都想学大数据开发?年轻人耗子尾汁吧~
  9. 今天的南京,很冷很冷
  10. vertical-align刨根问底