Retrofit官方文檔翻譯(原文連接:http://square.github.io/retrofit/)
本文翻譯純屬學習筆記記錄,若有涉及到版權問題請郵件(itingchunyu@163.com)我,我會當即撤銷展現,謝謝!git
Retrofit
改造你的HTTP API變成一個Java接口。github
public interface GitHubService {
@Get("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user)
}
複製代碼
Retrofit
類生成一個 GitHubService
接口的實現。express
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/") //可動態配置
.build();
//生成指定接口的實現
GitHubService service = retrofit.create(GitHubService.class);
複製代碼
由GitHubService
建立的每一個 Call
能夠同步或異步HTTP請求到遠程網絡服務器。apache
Call<List<Repo>> repos = service.listRepos("octocat");
複製代碼
使用註解去描述HTTP請求方式:json
接口方法經過註解的方式及其參數指示如何處理一個請求api
每一個方法必須擁有一個 HTTP
註解,去告知請求方式和相關調用Api。這裏有五種構造方式:GET, POST, PUT, DELETE, and HEAD.相關資源的URL被指定在註釋中。bash
@GET("users/list")
複製代碼
你也能夠在URL中指定查詢參數。服務器
@GET("users/list?sort=desc")
複製代碼
在方法中使用替換塊和參數能夠動態更新一個請求的URL。一個替換塊是一個字母數字字符串包圍{
和}
。相應的參數必須與@path
註釋使用相同的字符串標記。網絡
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
複製代碼
查詢參數也能夠被添加。app
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
複製代碼
對於複雜的查詢參數,參數能夠存放 Map
集合中。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
複製代碼
BODY
使用@Body
註釋一個對象,這個對象能夠做爲HTTP請求實體傳輸。
@POST("users/new")
Call<User> createUser(@Body User user);
複製代碼
經過Retrofit
實例初始化指定轉換器,如此這個被註釋的對象就能夠被轉換。若是初始化未指定,默認的RequestBody
被使用。
請求方法也能夠被聲明發送表單編碼和多部分數據方式提交。
當 @FormUrlEncoded
註釋出如今方法上,意味着請求以表單變編碼方式提交。所以每一個key-value
鍵值對參數必須被@Field
標記註釋,包含名稱和對應的值。
@FormUrlEncoded
@POST("user/edit")
Call<User> update(@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
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
複製代碼
你能夠根據須要在一個方法上使用@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);
複製代碼
注意,Headers
不會互相覆蓋。具備相同名稱的全部頭文件都包括在請求。一個請求的Headers
能夠動態更新。經過@Header
註釋相關參數傳入。若是傳入的值爲空,這個header將會被忽略。不然toString
方法將會被調用而且結果將被使用。
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization);
複製代碼
Headers
可使用OkHttp interceptor爲每一個請求統一指定headers。
Call
事例能被同步或異步執行。每一個事例僅僅能被使用一次,可是調用clone()
方法能夠建立一個副本能夠被從新使用。 在Android裏面,回調執行在主線程。在Java虛擬機中,回調將會發生在與發起HTTP請求同一個線程中。
Retrofit
是一種能將你的API接口轉化爲可調用的對象的類。默認狀況下,Retrofit
會給你默認配置項,但它容許你本身定製。
默認狀況下,Retrofit
能夠反序列化HTTP bodyies
爲OkHttp的ResponseBody
類型,而且它只接受RequestBody
實體爲@Body
註釋的類型。 轉換器也能夠添加其它類型支持。六個模塊適應現下主流的序列化庫爲你提供方便。
下面是一個使用GsonConverterFactory類生成GitHubService接口的實現的示例,該接口使用Gson進行反序列化。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonCoverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
複製代碼
若是您須要使用Retrofit不支持的內容格式(例如YAML,txt,自定義格式)的API進行通訊,或者您但願使用不一樣的庫來實現現有的格式,則能夠輕鬆地建立你本身的轉換器。 建立一個擴展了Converter.Factory類的類,並在構建適配器時傳遞一個實例。
Retrofit
的源代碼、事例你能夠在GitHub上查閱。
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.3.0</version>
</dependency>
複製代碼
compile 'com.squareup.retrofit2:retrofit:2.3.0'
複製代碼
Retrofit
要求最小Java7或Android 2.3.
若是你使用在你的項目中使用ProGuard
,你應該在你的混淆文件配置中添加下面對應混淆代碼:
# 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
的底層使用Okio
,因此你或許也須要了解ProGuard rules混淆規則。
Copyright 2013 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
複製代碼