简介
Type-safe HTTP client for Android and Java by Square, Inc.
GitHub主页:https://github.com/square/retrofit/
依赖与混淆
Retrofit requires at minimum Java 7 or Android 2.3.
Snapshots of the development version are available in Sonatype‘s snapshots repository.
compile ‘com.squareup.retrofit2:retrofit:2.3.0‘
Converters 转换器
compile ‘com.squareup.retrofit2:converter-gson:2.0.2‘
ProGuard 混淆
If you are using ProGuard you might need to add the following options:
-dontwarn okio.**
-dontwarn javax.annotation.**
Retrofit uses Okio under the hood(在后台,在底层), so you may want to look at its ProGuard rules as well.
配置OkHttpClient
很多时候,比如你使用Retrofit需要统一的log管理,给每个请求添加统一的header等,这些都应该通过OkHttpClient去操作。你可以单独写一个OkHttpClient的单例生成类,在这个里面完成你所需的所有的配置,然后将OkHttpClient实例通过方法公布出来,设置给retrofit。
Retrofit.Builder的callFactory方法接受一个okhttp3.Call.Factory对象,OkHttpClient即为它的一个实现类。
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(@NonNull Chain chain) throws IOException {
return null;
}
}).build();
Retrofit是什么?
Type-safe HTTP client for Android and Java by Square, Inc.
Retrofit 是一个 RESTful(一种架构风格)的 HTTP 网络请求框架的封装。注意这里并没有说它是网络请求框架,主要原因在于网络请求的工作并不是Retrofit 来完成的。Retrofit2.0 内置 OkHttp,Retrofit 得益于 OkHttp 的优势,较之于 Volley 是一种更加先进的网络框架。
Retrofit 专注于接口的封装,OkHttp 专注于网络请求的高效,二者分工协作!
我们的应用程序通过 Retrofit 请求网络,实际上是使用 Retrofit 接口层封装请求参数、Header、Url 等信息,之后由 OkHttp 完成后续的请求操作,在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,Retrofit 根据用户的需求对结果进行解析的过程。
Retrofit 2.0的变化
在Retrofit 2.0中,最大的改动莫过于减小库的体积。
- 首先,Retrofit 2.0去掉了对所有的HTTP客户端的兼容,而钟情于OkHttpClient一个,极大地减少了各种适配代码;
- 其次,拆库,比如将对RxJava的支持设置为可选(需要额外引入库);
- 再者,将各个序列化、反序列化转换器支持设置为可选(需要额外引入库)。
GitHub WiKi 使用指导
Call Adapters
Retrofit is pluggable allowing different execution mechanisms and their libraries to be used for performing the HTTP call. This allows API requests to seamlessly compose with any existing threading model and/or task framework in the rest of your app.
Retrofit是可插拔的,允许不同的执行机制及其库用于执行HTTP调用。 这允许API请求,与您应用程序其余部分中的,任何现有线程模型,和/或任务框架无缝组合。
These are called call adapters, and Retrofit includes a few first-party modules for popular frameworks:
这些被称为call适配器,而Retrofit为当前非常流行的框架提供了一些第一方模块(官方构件):
- RxJava
Observable
&Single
-com.squareup.retrofit2:adapter-rxjava
- RxJava2
Observable
,Flowable
,Single
,Completable
&Maybe
-com.squareup.retrofit2:adapter-rxjava2
- Guava
ListenableFuture
-com.squareup.retrofit2:adapter-guava
- Java 8
CompletableFuture
-com.squareup.retrofit2:adapter-java8
Various third-party adapters have been created by the community for other libraries:
社区也已经为其他库创建了各种的第三方适配器:
Converters 转换器
Retrofit is pluggable allowing different serialization formats and their libraries to be used for converting Java types to their HTTP representation and parsing HTTP entities back into Java types.
Retrofit 是可插拔的,允许不同的序列化格式及其库,用于将Java类型转换为其HTTP表示形式,并将HTTP实体解析为Java类型。
These are called converters, and Retrofit includes a few first-party modules for popular frameworks:
这些被称为转换器,而Retrofit为当前非常流行的框架提供了一些第一方模块(官方构件),:
- Gson -
com.squareup.retrofit2:converter-gson
- Jackson -
com.squareup.retrofit2:converter-jackson
- Moshi -
com.squareup.retrofit2:converter-moshi
- Protobuf -
com.squareup.retrofit2:converter-protobuf
- Wire -
com.squareup.retrofit2:converter-wire
- Simple Framework -
com.squareup.retrofit2:converter-simplexml
- Scalars -
com.squareup.retrofit2:converter-scalars
Two delegating converters are also provided:
另外,还提供了两个委托转换器:
- Guava‘s
Optional<T>
-com.squareup.retrofit2:converter-guava
- Java 8‘s
Optional<T>
-com.squareup.retrofit2:converter-java8
These differ from the normal converters in that they don‘t actually convert bytes to object. Instead, they delegate to a normal converter for that and then wrap the optionally-nullable resulting value into an Optional.
这些与正常转换器不同之处在于,它们实际上并不将字节转换为对象。 相反,它们委托给一个正常的转换器,然后将可选的可空值结果值包装为可选。
Various third-party converters have been created by the community for other libraries and serialization formats:
社区也已经为其他库和序列化格式,创建了各种的第三方转换器:
- LoganSquare -
com.github.aurae.retrofit2:converter-logansquare
- FastJson -
org.ligboy.retrofit2:converter-fastjson
ororg.ligboy.retrofit2:converter-fastjson-android
Retrofit Tutorials 推荐的教程资源
There are various Retrofit tutorials spread around the web and everyone is looking for help on different sites like Retrofit’s GitHub issues or Stackoverflow. Actually, there’s a tutorial series with more than 47 Retrofit guides available at Future Studio. Those guys are totally into Retrofit and help the community grow, make progress on problems and be awesome!
有各种各样的Retrofit教程遍布网络,每个人都在不同的网站寻找帮助,如Retrofit的GitHub issues或Stackoverflow。 实际上,在Future Studio上有一个具有超过47个可用的Retrofit指南的系列教程。 这些家伙完全进入了Retrofit,并且帮助社区发展,在解决问题上取得进展(大有裨益),并且很棒!
Find guides on topics like:
查找有关以下主题的指南:
- Getting Started with Retrofit 入门
- Retrofit 2 Upgrade Guide from 1.x 升级指南
- Handle authentication(处理认证) with Retrofit (Basic, custom OAuth 2, Token based, Hawk)
- Upload & download files
- Improve your development and debugging flow to test your app against multiple environments- and many more! 改进您的开发和调试流程,以测试您的应用程序对多个环境的适应 - 以及更多!
- Error Handling
You’ll find a lot more guides on various topics, have a look and benefit from all the solutions.
您可以在各种主题中找到更多指南,看一看并从所有这些解决方案中获益。
Enjoy coding and make your app rock!
享受编码,并让你的应用程序开始摇滚吧!
Square 官网使用教程
1、Introduction 基本使用介绍
Retrofit turns your HTTP API into a Java interface.
Retrofit可以将你的HTTP API转化为JAVA的接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
The Retrofit class generates an implementation of the GitHubService interface.
通过Retrofit的create方法,就能生成一个GitHubService接口的实现
Retrofit retrofit = new Retrofit.Builder()
GitHubService service = retrofit.create(GitHubService.class);
Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.
每一个"来自创建的GitHubService接口的"Call对象,都可以向远程Web服务器发出同步或异步的HTTP请求。
Call<List<Repo>> repos = service.listRepos("octocat");
Use annotations to describe the HTTP request:
- URL parameter replacement and query parameter support。
- Object conversion to request body (e.g., JSON, protocol buffers)。
- Multipart request body and file upload。
Retrofit使用注解来描述HTTP请求:
- URL参数的替换和query参数的支持
- 对象转化为请求体(如:JSON,protocol buffers等)
- 多重请求体和文件上传
2、API Declaration 接口方法声明
Annotations on the interface methods and its parameters indicate how a request will be handled.
接口方法上的注解及其参数,表明一个请求需要怎么样被处理。
【2.1、REQUEST METHOD 请求方法】
Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the annotation.
每一个方法必须要有一个HTTP注解,来标明请求的方式和相对URL。有五种内置的注解:GET、POST、PUT、DELETE以及HEAD。资源的相对URL需要在注解里面指定:
@GET("users/list")
You can also specify query parameters in the URL.
你也可以将query参数直接写在URL里:
@GET("users/list?sort=desc")
【2.2、URL MANIPULATION URL操作】
A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }. A corresponding parameter must be annotated with @Path using the same string.
一个请求的URL可以通过"替换块和方法的参数"来进行动态的更新。替换块是由被{}包裹起来的"字母数字字符串"。相应的参数必须使用@Path来注解同样的字符串。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
Query parameters can also be added.
Query参数也能同时被添加。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
For complex query parameter combinations a Map can be used.
对于复杂的query参数,可以用Map来构建
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
【2.3、REQUEST BODY 请求体】
An object can be specified for use as an HTTP request body with the @Body annotation.
可以通过@Body注解来指定一个对象作为HTTP请求主体
@POST("users/new")
Call<User> createUser(@Body User user);
The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.
这个对象会被Retrofit实例中指定的converter进行转化。如果没有给Retrofit实例添加任何converter,则只能使用RequestBody。
【2.4、FORM ENCODED AND MULTIPART 表单编码和多个】
Methods can also be declared to send form-encoded and multipart data.
方法也可以通过声明来发送form-encoded和multipart类型的数据。
Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing the name and the object providing the value.
当方法中存在@FormUrlEncoded注解时,会发送表单编码数据。每个键值对都(需要)用@Filed来注解,其中包含名称和提供该值对象。
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@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注解时,将使用Mutipart请求。Parts需要使用@Part注解来声明。
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Multipart parts use one of Retrofit‘s converters or they can implement RequestBody to handle their own serialization.
多个部件使用Retrofit其中的一个转换器,或者他们可以实现RequestBody来处理自己的序列化。
【2.5、HEADER MANIPULATION 头部操作】
You can set static headers for a method using the @Headers annotation.
你可以通过使用@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);
Note that headers do not overwrite each other. All headers with the same name will be included in the request.
请注意,头部参数并不会相互覆盖。具有同一个名称的所有头参数都会被包含进请求里面(即:允许key重复)。
A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.
可以使用@Header注解动态更新请求头。 相应的参数必须提供给 @Header 注解。 如果这个值为null,那么这个头部参数就会被忽略。 否则,值的 toString 方法将会被调用,并且使用此结果。
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
Headers that need to be added to every request can be specified using an OkHttp interceptor.
可以使用OkHttp拦截器来指定需要添加到每个请求中的头部参数。
【2.6、SYNCHRONOUS VS. ASYNCHRONOUS 同步 VS 异步】
Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling clone() will create a new instance that can be used.
你可以同步或者异步地来执行Call实例。每个实例只能被使用一次,但是调用 clone() 后将会创建一个可以使用的新的实例。
On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.
在Android中,callback将会在主线程中执行;而在JVM环境中,callback将发生在和执行Http请求相同的那个线程中。
3、Retrofit Configuration 配置
Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.
Retrofit是将你定义的API接口转换为可调用对象的类。 默认情况下,Retrofit会提供给你"对您的平台来说"比较理智的默认值,但它允许自定义。
【3.1、CONVERTERS 转换器】
By default, Retrofit can only deserialize HTTP bodies into OkHttp‘s ResponseBody type and it can only accept its RequestBody type for @Body.
默认情况下,Retrofit只能将HTTP消息体反序列化为OKHttp的 ResonseBody 类型,而且只能接收 RequestBody 类型作为 @Body。
Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.
可以添加转换器来支持其他类型。 以下六个同级模块,采用了常用的序列化库,来为你提供方便。
- Gson: com.squareup.retrofit2:converter-gson
- Jackson: com.squareup.retrofit2:converter-jackson
- Moshi: com.squareup.retrofit2:converter-moshi
- Protobuf: com.squareup.retrofit2:converter-protobuf
- Wire: com.squareup.retrofit2:converter-wire
- Simple XML: com.squareup.retrofit2:converter-simplexml
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
Here‘s an example of using the GsonConverterFactory class to generate an implementation of the GitHubService interface which uses Gson for its deserialization.
下面提供一个使用GsonConverterFactory类生成 GitHubService 的接口实现(通过使用Gson反序列化)的例子。
以下是使用GsonConverterFactory类生成使用Gson进行反序列化的GitHubService接口的实现的示例。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())//GsonConverterFactory
.build();
GitHubService service = retrofit.create(GitHubService.class);
【3.2、CUSTOM CONVERTERS 自定义转化器】
If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.
如果你需要与,没有使用Retrofit提供的内容格式的API,进行交互(例如YAML、txt、或自定义格式),或者是你希望使用一个不同的库,来实现现有的格式,你可以轻松创建你自己的转化器。你需要创建一个继承自Converter.Factory的类,并且在构建适配器的时候传递一个实例。
2017-9-7