关于Retrofit的使用介绍

本文为翻译Retrofit 官方文档 翻译不准确,所以配上英文。
此操作只为自己方便查看。

介绍 Introduction

改进将您的HTTP API转换为Java接口。
Retrofit turns your HTTP API into a Java interface.

public interface GitHubService {
  @GET("users/{user}/repos")
  Call> listRepos(@Path("user") String user);
}

新类生成GitHubService接口的实现。
The Retrofit class generates an implementation of the GitHubService interface.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

来自创建的GitHubService的每次调用都可以向远程webserver发出同步或异步HTTP请求。
Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.

Call> repos = service.listRepos("octocat");

使用注解来描述HTTP请求:
URL参数替换和查询参数支持
对象转换为请求体(例如,JSON,协议缓冲区)
多部分请求正文和文件上传

API声明 API Declaration

接口方法及其参数的注释表明如何处理请求。
Annotations on the interface methods and its parameters indicate how a request will be handled.

请求方法 REQUEST METHOD

每个方法都必须有一个HTTP注释,它提供了请求方法和相对URL。有5个内置注释:GET、POST、PUT、DELETE和HEAD。资源的相对URL是在注释中指定的。
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.

@GET("users/list")

您还可以在URL中指定查询参数。
You can also specify query parameters in the URL.

@GET("users/list?sort=desc")

URL 操作 URL MANIPULATION

可以使用该方法上的替换块和参数动态更新请求URL。替换块是由字母和字母组成的字母数字字符串。一个对应的参数必须使用相同的字符串用@path注释。
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.

@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId);

查询参数也可以添加。
Query parameters can also be added.

@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId, @Query("sort") String sort);

对于复杂的查询参数组合,可以使用映射。
For complex query parameter combinations a Map can be used.

@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId, @QueryMap Map options);

REQUEST BODY

一个对象可以被指定用作带有@body注释的HTTP请求体。
An object can be specified for use as an HTTP request body with the @Body annotation.

@POST("users/new")
Call createUser(@Body User user);

该对象还将使用在翻新实例上指定的转换器进行转换。如果不添加转换器,则只能使用RequestBody。
The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.

表单编码和多部分 FORM ENCODED AND MULTIPART

Methods can also be declared to send form-encoded and multipart data.

方法也可以被声明为发送表单编码和多部分数据。
当@formurlen编码出现在方法上时,会发送表单编码的数据。每个键值对都用@field标注,包含名称和提供值的对象。
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
@POST("user/edit")
Call updateUser(@Field("first_name") String first, @Field("last_name") String last);

当@Multipart出现在方法中时,会使用多部分请求。部件使用@part标注声明。
Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.

@Multipart
@PUT("user/photo")
Call 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.

头操作 HEADER MANIPULATION

您可以使用@headers注释为一个方法设置静态头部。
You can set static headers for a method using the @Headers annotation.

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call> widgetList();
@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call getUser(@Path("username") String username);

注意,标题不会相互覆盖。所有具有相同名称的头信息将包含在请求中。
可以使用@Header标注动态更新请求头。必须向@header提供相应的参数。如果值为null,则省略标题。否则,toString将被调用值,以及所使用的结果。
Note that headers do not overwrite each other. All headers with the same name will be included in the request.

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.

@GET("user")
Call getUser(@Header("Authorization") String authorization)

需要添加到每个请求的标头可以使用OkHttp拦截器指定。
Headers that need to be added to every request can be specified using an OkHttp interceptor.

同步与异步 SYNCHRONOUS VS. ASYNCHRONOUS

Call实例可以同步或异步执行。每个实例只能被使用一次,但是调用clone()将创建一个可以使用的新实例。
在Android上,回调将在主线程上执行。在JVM上,回调将发生在执行HTTP请求的同一线程上。
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.
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.

更新配置 Retrofit Configuration

翻新是您的API接口被转换成可调用对象的类。默认情况下,翻新会给你的平台带来合理的默认值,但它允许定制。
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.

转换器CONVERTERS

默认情况下,翻新只能将HTTP主体反序列化为OkHttp的ResponseBody类型,并且它只能接受它的RequestBody类型为@body。
By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.
可以添加转换器来支持其他类型。为了方便,6个兄弟模块调整流行的序列化库。
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
    这里有一个使用GsonConverterFactory类来生成GitHubService接口的实现的例子,该接口使用Gson进行反序列化。
    Here's an example of using the GsonConverterFactory class to generate an implementation of the GitHubService interface which uses Gson for its deserialization.
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

GitHubService service = retrofit.create(GitHubService.class);

自定义转换器 CUSTOM CONVERTERS

如果您需要与一个使用内容格式的API进行通信,该API使用的内容格式不支持box(例如YAML、txt、定制格式),或者您希望使用不同的库来实现现有格式,那么您可以轻松创建自己的转换器。创建一个扩展转换器的类。在构建适配器时,工厂类并传递一个实例。

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.

Download

↓ Latest JAR

在GitHub上可以找到更新的源代码,它的样本,以及这个网站。
The source code to the Retrofit, its samples, and this website is available on GitHub.

MAVEN


  com.squareup.retrofit2
  retrofit
  (insert latest version)

GRADLE

compile 'com.squareup.retrofit2:retrofit:(insert latest version)'

Retrofit requires at minimum Java 7 or Android 2.3.

PROGUARD
如果您在项目中使用了ProGuard,那么您的配置中会添加以下几行:
If you are using ProGuard in your project add the following lines to your configuration:

# 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

翻新使用的是在引擎盖下使用的,所以你可能也想看看它的ProGuard规则。
Retrofit uses Okio under the hood, so you may want to look at its ProGuard rules as well.

你可能感兴趣的:(关于Retrofit的使用介绍)