Retrofit官方文档翻译(原文连接:http://square.github.io/retrofit/)
本文翻译纯属学习笔记记录,若有涉及到版权问题请邮件(itingchunyu@163.com)我,我会当即撤销展现,谢谢!git
Retrofit
改造你的HTTP API变成一个Java接口。github
public interface GitHubService {
@Get("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user)
}
复制代码
Retrofit
类生成一个 GitHubService
接口的实现。express
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/") //可动态配置
.build();
//生成指定接口的实现
GitHubService service = retrofit.create(GitHubService.class);
复制代码
由GitHubService
建立的每一个 Call
能够同步或异步HTTP请求到远程网络服务器。apache
Call<List<Repo>> repos = service.listRepos("octocat");
复制代码
使用注解去描述HTTP请求方式:json
接口方法经过注解的方式及其参数指示如何处理一个请求api
每一个方法必须拥有一个 HTTP
注解,去告知请求方式和相关调用Api。这里有五种构造方式:GET, POST, PUT, DELETE, and HEAD.相关资源的URL被指定在注释中。bash
@GET("users/list")
复制代码
你也能够在URL中指定查询参数。服务器
@GET("users/list?sort=desc")
复制代码
在方法中使用替换块和参数能够动态更新一个请求的URL。一个替换块是一个字母数字字符串包围{
和}
。相应的参数必须与@path
注释使用相同的字符串标记。网络
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
复制代码
查询参数也能够被添加。app
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
复制代码
对于复杂的查询参数,参数能够存放 Map
集合中。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
复制代码
BODY
使用@Body
注释一个对象,这个对象能够做为HTTP请求实体传输。
@POST("users/new")
Call<User> createUser(@Body User user);
复制代码
经过Retrofit
实例初始化指定转换器,如此这个被注释的对象就能够被转换。若是初始化未指定,默认的RequestBody
被使用。
请求方法也能够被声明发送表单编码和多部分数据方式提交。
当 @FormUrlEncoded
注释出如今方法上,意味着请求以表单变编码方式提交。所以每一个key-value
键值对参数必须被@Field
标记注释,包含名称和对应的值。
@FormUrlEncoded
@POST("user/edit")
Call<User> update(@Field("first_name") String first, @Field("last_name") String last);
复制代码
Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
复制代码
你能够根据须要在一个方法上使用@Headers
设置静态的头参数配置。
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
复制代码
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
复制代码
注意,Headers
不会互相覆盖。具备相同名称的全部头文件都包括在请求。一个请求的Headers
能够动态更新。经过@Header
注释相关参数传入。若是传入的值为空,这个header将会被忽略。不然toString
方法将会被调用而且结果将被使用。
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization);
复制代码
Headers
可使用OkHttp interceptor为每一个请求统一指定headers。
Call
事例能被同步或异步执行。每一个事例仅仅能被使用一次,可是调用clone()
方法能够建立一个副本能够被从新使用。 在Android里面,回调执行在主线程。在Java虚拟机中,回调将会发生在与发起HTTP请求同一个线程中。
Retrofit
是一种能将你的API接口转化为可调用的对象的类。默认状况下,Retrofit
会给你默认配置项,但它容许你本身定制。
默认状况下,Retrofit
能够反序列化HTTP bodyies
为OkHttp的ResponseBody
类型,而且它只接受RequestBody
实体为@Body
注释的类型。 转换器也能够添加其它类型支持。六个模块适应现下主流的序列化库为你提供方便。
下面是一个使用GsonConverterFactory类生成GitHubService接口的实现的示例,该接口使用Gson进行反序列化。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonCoverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
复制代码
若是您须要使用Retrofit不支持的内容格式(例如YAML,txt,自定义格式)的API进行通讯,或者您但愿使用不一样的库来实现现有的格式,则能够轻松地建立你本身的转换器。 建立一个扩展了Converter.Factory类的类,并在构建适配器时传递一个实例。
Retrofit
的源代码、事例你能够在GitHub上查阅。
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.3.0</version>
</dependency>
复制代码
compile 'com.squareup.retrofit2:retrofit:2.3.0'
复制代码
Retrofit
要求最小Java7或Android 2.3.
若是你使用在你的项目中使用ProGuard
,你应该在你的混淆文件配置中添加下面对应混淆代码:
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
复制代码
因Retrofit
的底层使用Okio
,因此你或许也须要了解ProGuard rules混淆规则。
Copyright 2013 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
复制代码