Retrofit基础入门(1)
2015-12-10 00:50
591 查看
这是在一系列Retrofit文章的第一篇, 这个系列的文章主要通过用例来校验Retrofit的使用范围和扩展性。
用Retrofit实现Basic Authentication
这篇文章介绍Retrofit的基本使用,并创建一个可以和server通信的client端。
这里并不介绍Retrofit的基础入门,关于这些信息请访问该项目主页。
A type-safe REST client for Android and Java.
你可以使用注解去描述http请求,默认支持参数化的url,此外它对multipart request body和文件上传提供功能支持。
build.gradle
pom.xml
build.gradle
Retrofit2默认使用用OkHttp作为网络层,因此你并不需要明确地引入OkHttp作为依赖,除非你对OkHttp的版本有要求。
现在,工程已准备就绪,让我们创建一个client。
下面定义了Android客户端的基本类:
该
Retrofit 2 你需要明确地添加一个转换器。将下面一行添加到你的build.gradle以导入GSON转换器
现在,您需要添加转换器到你的Retrofit object里。在Retrofit的builder上调用
定义一个类Contributor。这个类包含映射响应数据时所需的属性。
关于JSON映射,GitHubClient只需定义了一个方法
在执行GitHub的例子时,你需要手动定义
我们希望你喜欢本篇的入门,然后使用Retrofit进行一个请求:)
Retrofit项目主页
Retrifit API定义文档
Bart Kiers的OAuth client
Retrofit example
android source
Retrofit 系列文章概览
基础入门用Retrofit实现Basic Authentication
这篇文章介绍Retrofit的基本使用,并创建一个可以和server通信的client端。
这里并不介绍Retrofit的基础入门,关于这些信息请访问该项目主页。
Retrofit是什么
官方描述:A type-safe REST client for Android and Java.
你可以使用注解去描述http请求,默认支持参数化的url,此外它对multipart request body和文件上传提供功能支持。
如何定义请求
请访问并阅读Retrofit主页的API部分,你会从那里的代码示例中获得对Retorfit基本的认识。准备一个android工程
现在,让我们打开电脑。如果您已经创建了一个Android工程,请继续下一步,否则在自己喜欢的IDE中,创建一个新工程。一般我们更喜欢使用gradle作为构建系统,当然你也可以使用Maven。添加依赖(Gradle 或者 Maven)
设置Retrofit依赖,根据您选择使用的编译系统,在pom.xml或build.gradle添加Retrofit依赖。然后运行build命令,构建系统会自动下载依赖库到您的项目中。我们建议使用Retrofi时把OkHTTP也添加到依赖项里。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.2.0</version> </dependency>
build.gradle
dependencies { // Retrofit & OkHttp compile 'com.squareup.retrofit:retrofit:1.9.0' compile 'com.squareup.okhttp:okhttp:2.2.0' }
Retrofit 2
用下面的依赖如果你用Retrofit 2pom.xml
<dependency> <groupId>com.squareup.retrofit</groupId> <artifactId>retrofit</artifactId> <version>2.2.0-beta2</version> </dependency>
build.gradle
dependencies { // Retrofit & OkHttp compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' }
Retrofit2默认使用用OkHttp作为网络层,因此你并不需要明确地引入OkHttp作为依赖,除非你对OkHttp的版本有要求。
现在,工程已准备就绪,让我们创建一个client。
Android client
在研究现有Retrofit的客户端时,找到了Bart Kiers的例子,实际上,它是一个使用Retrofit进行OAuth认证的例子。但是它包括了一个基础的client。因此我们把它作为基础,并在以后的博客文章进一步对其功能进行的扩展。下面定义了Android客户端的基本类:
ServiceGenerator。
ServiceGenerator
该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> 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 httpClient = new OkHttpClient(); 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(); return retrofit.create(serviceClass); } }
该
ServiceGenerator类使用Retrofit的
RestAdapter.Builder为一个给定的
API_BASE_URL创建一个新的REST client。例如,GitHub的
API_BASE_URL为https://developer.github.com/v3/。其中
serviceClass是api请求的接口。以下部分介绍Retrofit的具体使用并定义一个示例client。
JSON映射
Retrofit 1.9 默认带有谷歌的 GSON。你需要的就是给响应对象定义一个类,然后json类型的响应会自动通过GSON映射成你需要的类型。Retrofit 2 你需要明确地添加一个转换器。将下面一行添加到你的build.gradle以导入GSON转换器
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
现在,您需要添加转换器到你的Retrofit object里。在Retrofit的builder上调用
addConverterFactory(GsonConverterFactory.create())把GSON作为默认的JSON转换器。
Retrofit使用
让我们举个例子,定义一个到从GitHub的REST请求。首先,我们要创建一个接口,并定义所需的方法。GithHub客户端
下面的代码定义了GitHubClient和一个获取某个github项目贡献者的名单列表的方法。它还演示了Retrofit的路径参数替换功能(路径中的
{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 ); }
定义一个类Contributor。这个类包含映射响应数据时所需的属性。
static class Contributor { String login; int contributions; }
关于JSON映射,GitHubClient只需定义了一个方法
contributors,返回类型
List<Contributor>。Retrofit会确保服务器的响应会被正确映射(响应和这个类匹配的情况下)。
请求Example
下面的代码使用ServiceGenerator来获取数据,调用上面创建的
GitHubClient的
contributors方法来获取贡献者。这个代码片段是Retrofit的github-client示例的修改版本。
在执行GitHub的例子时,你需要手动定义
API_BASE_URL为https://developer.github.com/v3/。另一种选择是创建一个重载的CreateService()方法接受两个参数:client类和baseURL。
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 + ")"); } }
后续
下一篇文章讲解如何使用Retrofit实现basic authentication 。我们用代码示例来访问带有basic authentication的Web服务或需要用户名/电子邮件和密码的API。此外后续的文章中会讲解API认证(包括OAuth authentication)。我们希望你喜欢本篇的入门,然后使用Retrofit进行一个请求:)
参考资源
原文链接Retrofit项目主页
Retrifit API定义文档
Bart Kiers的OAuth client
Retrofit example
android source
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories