Retrofit简介与使用方法(翻译)

Posted on 2017-04-24 08:51  xl_phoenix  阅读(407)  评论(0编辑  收藏  举报

简介

Retrofit 是一个Square开发的类型安全的REST安卓客户端请求库。这个库为网络认证、API请求以及用OkHttp发送网络请求提供了强大的框架。Retrofit库让从web api下载JSON 或者xml数据变的非常简单直接。一旦数据下载完成即将其解析成普通java类(POJO)。

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生成了一个GitHubService接口的对象。

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

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的请求都可以设为同步或者异步的HTTP请求。

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

Use annotations to describe the HTTP request:

使用注释去描述HTTP请求

  • URL parameter replacement and query parameter support

  • Object conversion to request body (e.g., JSON, protocol buffers)

  • Multipart request body and file upload

  • 支持替换URL参数和询问参数

  • 对象可以转换成请求体(比如JSON,协议buffers)

  • 混合请求和文件上传

API声明

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

接口方法和参数的注释说明了请求将如何被使用。

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.

每一个方法必须具有提供了请求方法和URL的HTTP注释,这里有五种注释,GETPOSTPUTDELETE和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.

复杂的参数可以使用map。

@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.
一个对象可以通过@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实例,如果没有添加转换器,则只能使用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 @Field containing the name and the object providing the value.

@FormUrlEncoded代表发送表格编码。每一个键值对通过@Field声明,包括名称和提供值的对象。

@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注释声明。

@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 请求头操作

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.

注意头文件不能互相覆盖,所有相同名称的头文件必须包含在请求中。

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提供。如果值为空,则头会被删除。否则,将调用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 interceptor。

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.

调用实例可以同步或异步地执行。 每个实例只能使用一种,但是调用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类型,它只能接受@Body的RequestBody类型。

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类生成使用Gson进行反序列化的GitHubService接口的实现的示例。

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通信时,需要使用Retrofit不支持的内容格式(例如YAML,txt,自定义格式),或希望使用不同的库来实现现有格式,你可以轻松创建 你自己的转换器 创建一个扩展Converter.Factory类的类,并在构建适配器时传递一个实例。

原文网址:Retrofit A type-safe HTTP client for Android and Java

Copyright © 2024 xl_phoenix
Powered by .NET 9.0 on Kubernetes