Retrofit 是一个Square开发的类型安全的REST安卓客户端请求库。这个库为网络认证、API请求以及用OkHttp发送网络请求提供了强大的框架。Retrofit库让从web api下载JSON 或者xml数据变的很是简单直接。一旦数据下载完成即将其解析成普通java类(POJO)。
Retrofit turns your HTTP API into a Java interface.java
Retrofit将你的HTTP API请求变为一个Java接口git
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.github
Retrofit生成了一个GitHubService接口的对象。web
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.json
每个GitHubService的请求均可以设为同步或者异步的HTTP请求。api
Call<List<Repo>> repos = service.listRepos("octocat");
Use annotations to describe the HTTP request:安全
使用注释去描述HTTP请求网络
URL parameter replacement and query parameter supportapp
Object conversion to request body (e.g., JSON, protocol buffers)框架
Multipart request body and file upload
支持替换URL参数和询问参数
对象能够转换成请求体(好比JSON,协议buffers)
混合请求和文件上传
Annotations on the interface methods and its parameters indicate how a request will be handled.
接口方法和参数的注释说明了请求将如何被使用。
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")
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);
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。
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去处理本身的序列。
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。
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 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将为您的平台提供的默认值,但也容许自定义设置。
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.
能够添加转换器来支持其余类型,包括六个流行的兄弟模块适应流行的序列化库,方便你使用。
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);
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类的类,并在构建适配器时传递一个实例。