1. 程式人生 > >Retrofit 官方文件翻譯

Retrofit 官方文件翻譯


介紹

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