Retrofit 官方文档翻译

时间:2022-09-06 05:39:43


介绍

Retrofit 把 HTTP API 转成 a Java (接口)interface.

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

The Retrofit class 生成一个GitHubService interface的实现.

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

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

每一个从生成的GitHubService的 Call  可以 make 一个同步或者异步的 对远程服务器的HTTP 请求 .

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

Use 注解来描述 the HTTP request:

  • URL参数替换和查询参数支持
  • 对象转换为请求体 (e.g., JSON, protocol buffers)
  • 多部分请求体 and 文件上传

API 声明

Annotations on the interface methods and its parameters indicate how a request will be handled.

一个interface中方法注解和它的参数表明了如何处理请求

REQUEST METHOD

Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GETPOSTPUTDELETE, 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.

你也可以在url中指定查询参数;

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

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.

@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.

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

REQUEST BODY

请求体

An object can be specified for use as an HTTP request body with the @Body annotation.

一个对象可以被指定来作为http 请求体 ,用@body注释。

@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 RequestBodycan be used.

通过在特定的retrofit实例上用指定的转换器来转换特定对象。如果没有转换器,则只能用 requestbody.

FORM ENCODED AND MULTIPART

格式编码和多部件

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

也可以声明方法发送格式编码和多部分数据

Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Fieldcontaining the name and the object providing the value.

当@FormUrlEncoded is present 在方法上,格式编码数据可以被发送。每个key-value对用@Field来注释,包括名字和value对象。

@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 存在芸方法上的时候,使用多部件请求。用@part来注释parts;

@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来处理他们自己的序列化;

HEADER MANIPULATION

Header操作

You can set static headers for a method using the @Headers annotation.

可以用@headers注释为方法设置静态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.

注意:header不会相互覆盖。所有具有相同名称的头将包含在请求中。

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动态更新。必须提供相应的参数给@headers。如图值是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.

需要添加到每个请求头的header可以用OkHttp interceptor来统一加上。

SYNCHRONOUS VS. ASYNCHRONOUS

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实例可以被同步执行或者异步执行。每个实例只能被执行一次,但是calling 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上,回调在主线程执行。在jvm中,回调将在执行HTTP请求的同一线程上发生。

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 为平台提供合理的默认值,但是允许自定义。

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的ResponseBody类型,它只能接收它的RequestBody type for @body。

Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.

可以添加转换器以支持其他类型。为方便起见,六种模块适应流行的序列化库。

  • Gsoncom.squareup.retrofit2:converter-gson
  • Jacksoncom.squareup.retrofit2:converter-jackson
  • Moshicom.squareup.retrofit2:converter-moshi
  • Protobufcom.squareup.retrofit2:converter-protobuf
  • Wirecom.squareup.retrofit2:converter-wire
  • Simple XMLcom.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.

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

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

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.

如果需要使用一个API来进行通信,该API使用的内容格式不支持(例如YAML、TXT、自定义格式),或者您希望使用不同的库来实现现有格式,那么您可以轻松地创建自己的转换器。创建一个类继承Converter.Factory ,并在构建适配器时传递一个实例。

Download

↓ Latest JAR

The source code to the Retrofit, its samples, and this website is available on GitHub.

MAVEN

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>(insert latest version)</version>
</dependency>

GRADLE

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

Retrofit requires at minimum Java 7 or Android 2.3.

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

Retrofit uses Okio under the hood, so you may want to look at its ProGuard rules as well.

Retrofit使用Okio引擎,所以您可能也想看看它的PROGARD规则。

Contributing

If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.

When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code compiles by running mvn clean verify.

Before your code can be accepted into the project you must also sign the Individual Contributor License Agreement (CLA).

License