前言
如果看Retrofit的源碼會(huì)發(fā)現(xiàn)其實(shí)質(zhì)上就是對(duì)okHttp的封裝,使用面向接口的方式進(jìn)行網(wǎng)絡(luò)請(qǐng)求恐疲,利用動(dòng)態(tài)生成的代理類封裝了網(wǎng)絡(luò)接口請(qǐng)求的底層, 其將請(qǐng)求返回javaBean. 它非常適合于restful url格式的請(qǐng)求袭祟,使用更多的注解方式提供各種功能.
Retrofit 把REST API返回的數(shù)據(jù)轉(zhuǎn)化為Java對(duì)象淮椰,就像ORM框架那樣邮丰,把數(shù)據(jù)庫內(nèi)的存儲(chǔ)的數(shù)據(jù)轉(zhuǎn)化為相應(yīng)的Java bean對(duì)象。
那么我們知道Retrofit是一個(gè)類型安全的網(wǎng)絡(luò)框架轴咱,而且它是使用REST API的汛蝙,接下來我們看看什么是REST吧。
Resources Representational State Transfer
翻譯過來就是資源表現(xiàn)層狀態(tài)轉(zhuǎn)化
具體請(qǐng)參考我的博客理解RESTful架構(gòu)
更多關(guān)于REST的介紹:什么是REST - GitHub
首先朴肺,在gralde文件中引入后續(xù)要用到的庫窖剑。(以下是我參考的其它博文中的,其中的版本可能有點(diǎn)老,先不管那么多了,能跑起來再說, 等我試驗(yàn)完后把它們更新成最新的版本)
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.0.1'
接下來我們寫一個(gè)例子,并一步步進(jìn)行分析。
創(chuàng)建兩個(gè)類: 實(shí)體Bean和服務(wù)接口類
public static class Contributor {
public final String login;
public final int contributions;
public Contributor(String login, int contributions) {
this.login = login;
this.contributions = contributions;
}
@Override
public String toString() {
return "Contributor{" +
"login='" + login + '\'' +
", contributions=" + contributions +
'}';
}
}
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
接下來創(chuàng)建Retrofit2的實(shí)例戈稿,并設(shè)置BaseUrl和Gson轉(zhuǎn)換西土。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.build();
創(chuàng)建請(qǐng)求服務(wù),并為網(wǎng)絡(luò)請(qǐng)求方法設(shè)置參數(shù)
GitHub gitHubService = retrofit.create(GitHub.class);
Call> call = gitHubService.contributors("square", "retrofit");
最后鞍盗,請(qǐng)求網(wǎng)絡(luò)需了,并獲取響應(yīng)
try{
Response> response = call.execute(); // 同步
Log.d(TAG, "response:" + response.body().toString());
} catch (IOException e) {
e.printStackTrace();
}
Call是Retrofit中重要的一個(gè)概念跳昼,代表被封裝成單個(gè)請(qǐng)求/響應(yīng)的交互行為
通過調(diào)用Retrofit2的execute(同步)或者enqueue(異步)方法,發(fā)送請(qǐng)求到網(wǎng)絡(luò)服務(wù)器肋乍,并返回一個(gè)響應(yīng)(Response)鹅颊。
它具有如下特點(diǎn)
獨(dú)立的請(qǐng)求和響應(yīng)模塊
從響應(yīng)處理分離出請(qǐng)求創(chuàng)建
每個(gè)實(shí)例只能使用一次。
Call可以被克隆墓造。
支持同步和異步方法堪伍。
能夠被取消。
由于call只能被執(zhí)行一次觅闽,所以按照上面的順序再次執(zhí)行Call將會(huì)得到如下錯(cuò)誤帝雇。
java.lang.IllegalStateException: Already executed
我們可以通過clone,來克隆一份call蛉拙,從而可以重新調(diào)用一次這個(gè)接口
// clone
Call> call1 = call.clone();
// 5. 請(qǐng)求網(wǎng)絡(luò)尸闸,異步
call1.enqueue(new Callback>() {
@Override
public void onResponse(Response> response, Retrofit retrofit) {
Log.d(TAG, "response:" + response.body().toString());
}
@Override
public void onFailure(Throwable t) {
}
});
下面我們總結(jié)一下使用retrofit的基本步驟
定義網(wǎng)絡(luò)請(qǐng)求的實(shí)體bean和服務(wù)接口類
創(chuàng)建retrofit2的實(shí)例
在這里需要設(shè)置baseUrl
設(shè)置一個(gè)OkHttpClient類的實(shí)例,可以是默認(rèn)的,也可以是定制的,如果有需要可以整體app使用一個(gè)單例實(shí)例. 有空再單獨(dú)說一下這個(gè)事.
設(shè)置Gson等轉(zhuǎn)換器
創(chuàng)建請(qǐng)求服務(wù)代理類, 并為網(wǎng)絡(luò)請(qǐng)求方法設(shè)置參數(shù),生成一個(gè)Call對(duì)象
請(qǐng)求網(wǎng)絡(luò), 并獲取響應(yīng)
支持execute(同步)和 enqueue(異步)
Call只能執(zhí)行一次
能夠被取消
Retrofit需要注解接口的請(qǐng)求方法和方法的參數(shù)來表明該請(qǐng)求需要怎么樣的處理。
每一個(gè)方法必須要有一個(gè)HTTP注解來標(biāo)明請(qǐng)求的方式和相對(duì)URL孕锄。有五種內(nèi)置的注解方式:GET吮廉、POST、PUT硫惕、DELETE以及HEAD茧痕。資源的相對(duì)URL需要在注解里面明確給出:
@GET("users/list")
當(dāng)然作為特殊用法: 你也可以將query參數(shù)直接寫死在URL里
@GET("users/list?sort=desc")
包括路徑的替換, 參數(shù)的替換, 請(qǐng)求頭參數(shù), post請(qǐng)求, 表單等
路徑替換
interface SomeService {
@GET("/some/endpoint/{thing}")
Call someEndpoint(
@Path("thing") String thing);
}
someService.someEndpoint("bar");
// GET /some/endpoint/bar HTTP/1.1
固定查詢參數(shù)
// 服務(wù)
interface SomeService {
@GET("/some/endpoint?fixed=query")
Call someEndpoint();
}
// 方法調(diào)用
someService.someEndpoint();
// 請(qǐng)求頭
// GET /some/endpoint?fixed=query HTTP/1.1
動(dòng)態(tài)參數(shù)
// 服務(wù)
interface SomeService {
@GET("/some/endpoint")
Call someEndpoint(
@Query("dynamic") String dynamic);
}
// 方法調(diào)用
someService.someEndpoint("query");
// 請(qǐng)求頭
// GET /some/endpoint?dynamic=query HTTP/1.1
動(dòng)態(tài)參數(shù)(Map)
// 服務(wù)
interface SomeService {
@GET("/some/endpoint")
Call someEndpoint(
@QueryMap Map dynamic);
}
// 方法調(diào)用
someService.someEndpoint(
Collections.singletonMap("dynamic", "query"));
// 請(qǐng)求頭
// GET /some/endpoint?dynamic=query HTTP/1.1
省略動(dòng)態(tài)參數(shù)
interface SomeService {
@GET("/some/endpoint")
Call someEndpoint(
@Query("dynamic") String dynamic);
}
// 方法調(diào)用
someService.someEndpoint(null);
// 請(qǐng)求頭
// GET /some/endpoint HTTP/1.1
固定+動(dòng)態(tài)參數(shù)
interface SomeService {
@GET("/some/endpoint?fixed=query")
Call someEndpoint(
@Query("dynamic") String dynamic);
}
// 方法調(diào)用
someService.someEndpoint("query");
// 請(qǐng)求頭
// GET /some/endpoint?fixed=query&dynamic=query HTTP/1.1
固定頭
interface SomeService {
@GET("/some/endpoint")
@Headers("Accept-Encoding: application/json")
Call someEndpoint();
}
someService.someEndpoint();
// GET /some/endpoint HTTP/1.1
// Accept-Encoding: application/json
動(dòng)態(tài)頭
interface SomeService {
@GET("/some/endpoint")
Call someEndpoint(
@Header("Location") String location);
}
someService.someEndpoint("Droidcon NYC 2015");
// GET /some/endpoint HTTP/1.1
// Location: Droidcon NYC 2015
固定+動(dòng)態(tài)頭
interface SomeService {
@GET("/some/endpoint")
@Headers("Accept-Encoding: application/json")
Call someEndpoint(
@Header("Location") String location);
}
someService.someEndpoint("Droidcon NYC 2015");
// GET /some/endpoint HTTP/1.1
// Accept-Encoding: application/json
// Location: Droidcon NYC 2015
Post請(qǐng)求野来,無Body
interface SomeService {
@POST("/some/endpoint")
Call someEndpoint();
}
someService.someEndpoint();
// POST /some/endpoint?fixed=query HTTP/1.1
// Content-Length: 0
Post請(qǐng)求有Body
interface SomeService {
@POST("/some/endpoint")
Call someEndpoint(
@Body SomeRequest body);
}
someService.someEndpoint();
// POST /some/endpoint HTTP/1.1
// Content-Length: 3
// Content-Type: greeting
//
// Hi!
表單編碼字段
interface SomeService {
@FormUrlEncoded
@POST("/some/endpoint")
Call someEndpoint(
@Field("name1") String name1,
@Field("name2") String name2);
}
someService.someEndpoint("value1", "value2");
// POST /some/endpoint HTTP/1.1
// Content-Length: 25
// Content-Type: application/x-www-form-urlencoded
//
// name1=value1&name2=value2
表單編碼字段(Map)
interface SomeService {
@FormUrlEncoded
@POST("/some/endpoint")
Call someEndpoint(
@FieldMap Map names);
}
someService.someEndpoint(
// ImmutableMap是OKHttp中的工具類
ImmutableMap.of("name1", "value1", "name2", "value2"));
// POST /some/endpoint HTTP/1.1
// Content-Length: 25
// Content-Type: application/x-www-form-urlencoded
//
// name1=value1&name2=value2
可以通過@Multipart注解方法
來發(fā)送Mutipart請(qǐng)求恼除。每個(gè)部分需要使用@Part來注解。
@Multipart
@PUT("user/photo")
Call updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
// 多個(gè)請(qǐng)求部分需要使用Retrofit的converter或者是自己實(shí)現(xiàn) RequestBody來處理自己內(nèi)部的數(shù)據(jù)序列化曼氛。
這幾個(gè)未深入的學(xué)習(xí), 著急學(xué)習(xí)的同學(xué)可以參考Retrofit2 完全解析 探索與okhttp之間的關(guān)系
這個(gè)其實(shí)我覺得直接使用okhttp就好了豁辉,使用retrofit去做這個(gè)事情真的有點(diǎn)瞎用的感覺~~
…
Retrofit類會(huì)通過你定義的API接口轉(zhuǎn)化為可調(diào)用的對(duì)象。默認(rèn)情況下舀患,Retrofit會(huì)返還給你合理的默認(rèn)值徽级,但也允許你進(jìn)行指定。
默認(rèn)情況下聊浅,Retrofit只能將HTTP體反序列化為OKHttp的 ResonseBody 類型餐抢,而且只能接收 RequestBody類型作為 @Body。
轉(zhuǎn)化器的加入可以用于支持其他的類型低匙。以下六個(gè)同級(jí)模塊采用了常用的序列化庫來為你提供方便旷痕。
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
下面提供一個(gè)使用GsonConverterFactory類生成 GitHubService的接口實(shí)現(xiàn)gson反序列化的例子。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
自定義轉(zhuǎn)化器
如果你需要與沒有使用Retrofit提供的內(nèi)容格式的API進(jìn)行交互的話或者是你希望使用一個(gè)不同的庫來實(shí)現(xiàn)現(xiàn)有的格式顽冶,你也可以輕松創(chuàng)建使用自己的轉(zhuǎn)化器欺抗。
你需要?jiǎng)?chuàng)建一個(gè)繼承自Converter.Factory的類并且在構(gòu)建適配器的時(shí)候加入到實(shí)例里面。
可插拔的執(zhí)行機(jī)制(Multiple, pluggable execution mechanisms)
interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
// Call 代表的是CallBack回調(diào)機(jī)制
Call> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo);
@GET("/repos/{owner}/{repo}/contributors")
// Observable 代表的是RxJava的執(zhí)行
Observable> repoContributors2(
@Path("owner") String owner,
@Path("repo") String repo);
@GET("/repos/{owner}/{repo}/contributors")
Future> repoContributors3(
@Path("owner") String owner,
@Path("repo") String repo);
}
注意强重,要在構(gòu)建Retrofit時(shí)指定適配器模式為RxJavaCallAdapterFactory
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("http://www.duitang.com")
.build();
否則绞呈,會(huì)報(bào)出如下錯(cuò)誤:
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for rx.Observable. Tried:
* retrofit.ExecutorCallAdapterFactory
這個(gè)需要簡(jiǎn)單提一下贸人,很多時(shí)候,比如你使用retrofit需要統(tǒng)一的log管理佃声,給每個(gè)請(qǐng)求添加統(tǒng)一的header等艺智,這些都應(yīng)該通過okhttpclient去操作,比如addInterceptor
例如:
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor()//log圾亏,統(tǒng)一的header等
{
@Override
public okhttp3.Response intercept(Chain chain) throws IOException
{
return null;
}
}).build();
或許你需要更多的配置力惯,你可以單獨(dú)寫一個(gè)OkhttpClient的單例生成類,在這個(gè)里面完成你所需的所有的配置召嘶,然后將OkhttpClient實(shí)例通過方法公布出來父晶,設(shè)置給retrofit。
設(shè)置方式:
Retrofit retrofit = new Retrofit.Builder()
.callFactory(OkHttpUtils.getClient())
.build();
callFactory方法接受一個(gè)okhttp3.Call.Factory對(duì)象弄跌,OkHttpClient即為此Factory類的一個(gè)實(shí)現(xiàn)類
如果你的工程中使用了代碼混淆甲喝,那么你的配置中需要添加一下的幾行
-dontwarn retrofit2.
-keep class retrofit2.
{ *; }
-keepattributes Signature
-keepattributes Exceptions
Retrofit作為一個(gè)上層框架,自然有很多底層lib庫支持铛只,okio和okhttp都包含其中埠胖。