1. Getting Started and Create an Android Client

1. Getting Started and Create an Android Client

Retrofit

tutorial

    • 什么是 Retrofit
    • 如何申明请求
    • 准备 Android 项目
    • 使用 Gradle 或 Maven 定义依赖
      • Retrofit 1.9 的依赖定义

        • pom.xml
        • build.gradle
      • Retrofit 2.0 的依赖定义
        • pom.xml
        • build.gradle
    • 持续发展的 Android 客户端
      • 服务生成器

        • Retrofit 1.9
        • Retrofit 2
    • JSON 映射
    • 使用 Retrofit
      • GitHub 客户端

        • Retrofit 1.9
        • Retrofit 2
    • Request 示例
      • Retrofit 1.9
      • Retrofit 2

该篇讲述了 Retrofit 的基础知识,并讲述了如何创建 Android 客户端的 APIHTTP 请求。

但是,本篇不会覆盖太多起步知识。如果想知道这些信息,请参见 主页 的内容。

什么是 Retrofit



Retrofit 的官网是这样描述的:

A type-safe REST client for Android and Java

因此,在 Retrofit 中,默认使用注解来描述 HTTP 请求、URL 参数占位符等操作。此外,它还支持多个请求体,也提供了文件上传的能力。

如何申明请求



请访问 Retrofit 的主页 ,阅读 API 申明部分,以便获取如何创建请求的感觉。在那里,既有重要的说明,又有示例代码。

准备 Android 项目



如果你已经创建了 Android 项目,那请跳过本段。如果没有,就使用你最喜欢的 IDE 来创建一个 Android 项目。推荐使用 Gradle 作为构建系统,当然,也可以使用 Maven

使用 Gradle 或 Maven 定义依赖



依赖于构建工具的不同,依赖定义的地方也不同,在 pom.xmlbuild.gradle 中定义依赖。

Retrofit 1.9 的依赖定义

pom.xml


  1. <dependency>


  2. <groupId>com.squareup.retrofit</groupId> 

  3. <artifactId>retrofit</artifactId> 

  4. <version>1.9.0</version> 

  5. </dependency>  

  6. <dependency>  

  7. <groupId>com.squareup.okhttp</groupId> 

  8. <artifactId>okhttp</artifactId> 

  9. <version>2.7.2</version> 

  10. </dependency>  

build.gradle


  1. dependencies {


  2. // Retrofit & OkHttp 

  3. compile ‘com.squareup.retrofit:retrofit:1.9.0‘ 

  4. compile ‘com.squareup.okhttp:okhttp:2.7.2‘ 



Retrofit 2.0 的依赖定义

pom.xml


  1. <dependency>


  2. <groupId>com.squareup.retrofit2</groupId> 

  3. <artifactId>retrofit</artifactId> 

  4. <version>2.1.0</version> 

  5. </dependency>  

  6. <dependency>  

  7. <groupId>com.squareup.retrofit2</groupId> 

  8. <artifactId>converter-gson</artifactId> 

  9. <version>2.1.0</version> 

  10. </dependency>  

build.gradle


  1. dependencies {


  2. // Retrofit & OkHttp 

  3. compile ‘com.squareup.retrofit2:retrofit:2.1.0‘ 

  4. compile ‘com.squareup.retrofit2:converter-gson:2.1.0‘ 



Retrofit 2 默认使用 OKHttp 作为网络层,并且基于它进行构建。因此,在项目中不需要显示的定义这个依赖,除非你需要一个不同的版本。

到现在为止,你的 Android 项目已经为 Retrofit 做好准备了,让我们创建一个持久的 Android API/Http 的客户端吧。

持续发展的 Android 客户端



在对已经存在的 Android 客户端的调研中,由 Bart Kiers 创建的 example repository示例 崭露头角。其实,它是一个使用 Retrofit 进行 OAuth 认证的示例。但是,对于一个可持续发展的客户端来说,它提供了所有必要的元素。这就是为什么我们将把它当作一个稳定版来使用,并在后面的教程中给它扩展高级的认证功能。

下面的类:ServiceGenerator 定义了 Android 客户端的基础。

服务生成器



ServiceGeneratorAPI/HTTP 客户端的核心。在当前的状态中,它仅仅定义了一个方法,用于使用给定的类创建 REST 类型的适配器,下面是代码:

Retrofit 1.9


  1. public class ServiceGenerator {



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


  3. private static RestAdapter.Builder builder = new RestAdapter.Builder() 

  4. .setEndpoint(API_BASE_URL) 

  5. .setClient(new OkClient(new OkHttpClient())); 


  6. public static <S> S createService(Class<S> serviceClass) { 

  7. RestAdapter adapter = builder.build(); 

  8. return adapter.create(serviceClass); 





Retrofit 2


  1. public class ServiceGenerator {



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


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


  4. private static Retrofit.Builder builder = 

  5. new Retrofit.Builder() 

  6. .baseUrl(API_BASE_URL) 

  7. .addConverterFactory(GsonConverterFactory.create()); 


  8. public static <S> S createService(Class<S> serviceClass) { 

  9. Retrofit retrofit = builder.client(httpClient.build()).build(); 

  10. return retrofit.create(serviceClass); 





ServiceGenerator 基于一个基本的地址,使用 RetrofitRestAdapter - Builder,创建了一个新的 REST 客户端。例如,GitHub 的基本地址是:https://api.github.com/。该类中定义了用于 API 请求的、有注解的类和接口。下面的章节显示了 Retrofit 具体的用法,并演示如何定义一个典范式的客户端。

JSON 映射



Retrofit 1.9 默认集成了 Google GSON。你要做的就是定义你所需的用于响应的对象类,响应将会被自动映射。

Retrofit 2 中,需要自己显式地为 Retrofit 对象添加转换器。上面的示例,在 build.gradle 文件中添加了下面的代码来引入 Retrofit 2 使用的 GSON 转换器:

  1. compile ‘com.squareup.retrofit2:converter-gson:2.1.0‘


现在,需要给 Retrofit 对象添加转换器,给 Retrofit Builder 对象使用 addConverterFactory(GsonConverterFactory.create()) 方法来为对象集成 GSON 用为它的默认转换器。

使用 Retrofit



好了,现在让我们定义一个 REST 客户端从 GitHub 上请求数据。首先,得创建接口、定义方法。

GitHub 客户端



下面的代码定义了一个 GitHubClient,和一个用于获取某个仓库贡献者列表的方法。代码来演示了 Retrofit 参数占位符功能(定义在路径中的 {owner}repo)的用法,它们的作用是:在方法被调用时,占位符将被替换为传入的变量。

Retrofit 1.9


  1. public interface GitHubClient {


  2. @GET("/repos/{owner}/{repo}/contributors") 

  3. List<Contributor> contributors( 

  4. @Path("owner") String owner, 

  5. @Path("repo") String repo 

  6. ); 



Retrofit 2


  1. public interface GitHubClient {


  2. @GET("/repos/{owner}/{repo}/contributors") 

  3. Call<List<Contributor>> contributors( 

  4. @Path("owner") String owner, 

  5. @Path("repo") String repo 

  6. ); 



下面是 Contributor 类的定义,类中必须的属性与响应数据映射相对应:

  1. static class Contributor {


  2. String login; 

  3. int contributions; 



关于先前提到的 JSON 映射:GitHubClient 类定义了名为 contributors 的方法,它的返回类型是 ListRetrofit 确保了服务响应能被正确的匹配(也就是响应匹配为相应的类)。

Request 示例



下面的代码片断演示了使用 ServiceGenerator 类实例化客户端,具体就是 GitHubClient,使用创建的客户端可以获取贡献者。这里的片断显示的是一个改进版。

在运行 GitHub 示例中,需要手动给 ServiceGenerator 设置基本网址,示例中是 https://api.github.com

Retrofit 1.9

  1. public static void main(String... args) {


  2. // Create a very simple REST adapter which points the GitHub API endpoint. 

  3. GitHubClient client = ServiceGenerator.createService(GitHubClient.class); 


  4. // Fetch and print a list of the contributors to this library. 

  5. List<Contributor> contributors = 

  6. client.contributors("fs_opensource", "android-boilerplate"); 


  7. for (Contributor contributor : contributors) { 

  8. System.out.println( 

  9. contributor.login + " (" + contributor.contributions + ")"); 





Retrofit 2


  1. public static void main(String... args) {


  2. // Create a very simple REST adapter which points the GitHub API endpoint. 

  3. GitHubClient client = ServiceGenerator.createService(GitHubClient.class); 


  4. // Fetch and print a list of the contributors to this library. 

  5. Call<List<Contributor>> call = 

  6. client.contributors("fs_opensource", "android-boilerplate"); 


  7. try { 

  8. List<Contributor> contributors = call.execute().body(); 

  9. } catch (IOException e) { 

  10. // handle errors 




  11. for (Contributor contributor : contributors) { 

  12. System.out.println( 

  13. contributor.login + " (" + contributor.contributions + ")"); 





时间: 2024-08-07 00:17:50

1. Getting Started and Create an Android Client的相关文章

Android Client 与 C# Server 的Socket通信

C# Socket Server 1.建立C# SocketServer 1 private void ServerStart() 2          { 3              //创建IPEndPoint 4              IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234); 5              //创建Socket实例 6              server_S

Android Client and Jsp Server

1. Interestfriend Server https://github.com/eltld/Interestfriend_server https://github.com/774663576/Interestfriend_server https://github.com/eltld/quyou_web Client https://github.com/774663576/Interestfriend https://github.com/eltld/Interestfriend 2

android client随机验证码生成函数

由于该项目使用验证码.自己找了一些资料.尽量把这个验证码做出来.代码不是很,較的简单,以下给大家看看我是怎么实现该功能的: 源代码地址下载:http://download.csdn.net/detail/u014608640/7268905 首先当然是写XML咯,贴上代码 <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:

Android Client and PHP Server

1 FEApplication https://github.com/eltld/FEApplication https://github.com/eltld/FE-web https://github.com/eltld/FEMobile https://github.com/eltld/FEMobile2 2. https://github.com/eltld/siscoe-mobile https://github.com/eltld/siscoe-web-android

Retrofit所有知识场景汇总

https://futurestud.io/blog/retrofit-getting-started-and-android-client Retrofit Series Overview Getting Started and Create an Android Client Basic Authentication on Android Token Authentication on Android OAuth on Android Multiple Query Parameters of

转载:怎样用通俗的语言解释REST,以及RESTful?

作者:覃超链接:https://www.zhihu.com/question/28557115/answer/48094438来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. URL定位资源,用HTTP动词(GET,POST,DELETE,DETC)描述操作. --- 简洁版 --- 0. REST不是"rest"这个单词,而是几个单词缩写.但即使那几个单词说出来,也无法理解在说什么 -_-!! (不是要贬低人,是我自己也理解困难):1. REST描述的是

RESTful 的通俗解释

转载自知乎,通俗易懂的讲解了RESTful链接:https://www.zhihu.com/question/28557115/answer/48094438 REST -- REpresentational State Transfer 直接翻译:表现层状态转移.这个中文直译经常出现在很多博客中.尼玛谁听得懂"表现层状态转移"? @Ivony 老师的一句话概括很精辟:URL定位资源,用HTTP动词(GET,POST,DELETE,DETC)描述操作.--- 简洁版 --- 0. RE

Mac Error Create Android Project - “Errors running builder &#39;Android Resource Manager&#39; on project”

http://stackoverflow.com/questions/18096315/mac-error-create-android-project-errors-running-builder-android-resource-man 在mac笔记本上运行android eclipse报标题的错误,然后在stackoverflow上找到了答案 18down votefavorite 5 I spent the whole day just trying to create a simple

[Quote] How To Change, Customize &amp; Create Android Boot Animation [Guide]

From http://www.addictivetips.com/mobile/how-to-change-customize-create-android-boot-animation-guide/ How To Change, Customize & Create Android Boot Animation [Guide] by Haroon Q Raja onMay 19, 2011 55 The boot animation is the first thing that you s