[譯] Retrofit官方文檔最佳實踐

Retrofit

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

  • URL中參數支持根據傳入的查詢參數動態調用替換
  • 對象與請求實體的轉換(如:JSON,protocol buffers)
  • 多請求實體和文件上傳支持

API 聲明

接口方法經過註解的方式及其參數指示如何處理一個請求api

請求方式

每一個方法必須擁有一個 HTTP 註解,去告知請求方式和相關調用Api。這裏有五種構造方式:GET, POST, PUT, DELETE, and HEAD.相關資源的URL被指定在註釋中。bash

@GET("users/list")
複製代碼

你也能夠在URL中指定查詢參數。服務器

@GET("users/list?sort=desc")
複製代碼

URL相關操做

在方法中使用替換塊和參數能夠動態更新一個請求的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設置靜態的頭參數配置。

@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。

同步Vs異步

Call 事例能被同步或異步執行。每一個事例僅僅能被使用一次,可是調用clone()方法能夠建立一個副本能夠被從新使用。 在Android裏面,回調執行在主線程。在Java虛擬機中,回調將會發生在與發起HTTP請求同一個線程中。

Retrofit配置

Retrofit是一種能將你的API接口轉化爲可調用的對象的類。默認狀況下,Retrofit會給你默認配置項,但它容許你本身定製。

轉換器

默認狀況下,Retrofit能夠反序列化HTTP bodyies爲OkHttp的ResponseBody類型,而且它只接受RequestBody實體爲@Body註釋的類型。 轉換器也能夠添加其它類型支持。六個模塊適應現下主流的序列化庫爲你提供方便。

  • 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

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

Download

V2.3.0 JAR

Retrofit的源代碼、事例你能夠在GitHub上查閱。

Maven

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>2.3.0</version>
</dependency>
複製代碼

Gradle依賴

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混淆規則。


License

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.
複製代碼
相關文章
相關標籤/搜索