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類的類,並在構建適配器時傳遞一個實例。