Retrofit
Retrofit是Square公司開(kāi)發(fā)的一款針對(duì)Android網(wǎng)絡(luò)請(qǐng)求的框架询筏,Retrofit2底層基于OkHttp實(shí)現(xiàn)的垄琐,OkHttp現(xiàn)在已經(jīng)得到Google官方認(rèn)可负蚊,大量的app都采用OkHttp做網(wǎng)絡(luò)請(qǐng)求福扬。
首先先來(lái)看一個(gè)完整Get請(qǐng)求是如何實(shí)現(xiàn):
創(chuàng)建業(yè)務(wù)請(qǐng)求接口华坦,具體代碼如下:
public interface ShopService {
@GET("book/search")
Call<BookSearchResponse> getSearchBooks(@Query("q") String name,
@Query("tag") String tag,
@Query("start") int start,
@Query("count") int count);
}
@GET注解就表示get請(qǐng)求实辑,
@Query表示請(qǐng)求參數(shù),將會(huì)以key=value的方式拼接在url后面
需要?jiǎng)?chuàng)建一個(gè)Retrofit的示例买雾,并完成相應(yīng)的配置
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.douban.com/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
BlueService service = retrofit.create(BlueService.class);
這里的baseUrl就是網(wǎng)絡(luò)請(qǐng)求URL相對(duì)固定的地址把曼,一般包括請(qǐng)求協(xié)議(如Http)、域名或IP地址漓穿、端口號(hào)等嗤军,當(dāng)然還會(huì)有很多其他的配置,推薦在Application中進(jìn)行初始化工作晃危,使用時(shí)通過(guò)Get方法獲取一個(gè)Retrofit實(shí)例叙赚。
還有addConverterFactory方法表示需要用什么轉(zhuǎn)換器來(lái)解析返回值,GsonConverterFactory.create()表示調(diào)用Gson庫(kù)來(lái)解析json返回值僚饭。
調(diào)用請(qǐng)求方法震叮,并得到Call實(shí)例
Call<BookSearchResponse> call = mBlueService.getSearchBooks("小王子", "", 0, 3);
Call其實(shí)在Retrofit中就是行使網(wǎng)絡(luò)請(qǐng)求并處理返回值的類,調(diào)用的時(shí)候會(huì)把需要拼接的參數(shù)傳遞進(jìn)去鳍鸵,此處最后得到的url完整地址https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&tag=&start=0&count=3
使用Call實(shí)例完成同步或異步請(qǐng)求
- 同步請(qǐng)求
BookSearchResponse response = call.execute().body();
這里需要注意的是網(wǎng)絡(luò)請(qǐng)求一定要在子線程中完成苇瓣,不能直接在UI線程執(zhí)行,不然會(huì)crash
- 異步請(qǐng)求
call.enqueue(new Callback<BookSearchResponse>() {
@Override
public void onResponse(Call<BookSearchResponse> call,Response<BookSearchResponse> response)
{
asyncText.setText("異步請(qǐng)求結(jié)果: " + response.body().books.get(0).altTitle);
}
@Override
public void onFailure(Call<BookSearchResponse> call, Throwable t) {
}
});
如何使用
首先需要在build.gradle文件中引入需要的第三包偿乖,配置如下:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'
如果使用RxJava击罪,還需引入以下依賴
compile 'io.reactivex:rxjava:1.1.10'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
引入完第三包接下來(lái)就可以使用Retrofit來(lái)進(jìn)行網(wǎng)絡(luò)請(qǐng)求了哲嘲。
Get方法
@Query
Get方法請(qǐng)求參數(shù)都會(huì)以key=value的方式拼接在url后面,Retrofit提供了兩種方式設(shè)置請(qǐng)求參數(shù)媳禁。
第一種就是像上面示例提到的直接在interface中添加@Query注解眠副,
還有一種方式是通過(guò)Interceptor實(shí)現(xiàn),直接看如何通過(guò)Interceptor實(shí)現(xiàn)請(qǐng)求參數(shù)的添加竣稽。
public class CustomInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl httpUrl = request.url().newBuilder()
.addQueryParameter("token", "tokenValue")
.build();
request = request.newBuilder().url(httpUrl).build();
return chain.proceed(request);
}
}
addQueryParameter就是添加請(qǐng)求參數(shù)的具體代碼囱怕,這種方式比較適用于所有的請(qǐng)求都需要添加的參數(shù),一般現(xiàn)在的網(wǎng)絡(luò)請(qǐng)求都會(huì)添加token作為用戶標(biāo)識(shí)丧枪,那么這種方式就比較適合光涂。
創(chuàng)建完成自定義的Interceptor后,還需要在Retrofit創(chuàng)建client處完成添加
.addInterceptor(new CustomInterceptor())
@QueryMap
如果Query參數(shù)比較多拧烦,那么可以通過(guò)@QueryMap方式將所有的參數(shù)集成在一個(gè)Map統(tǒng)一傳遞忘闻,
還以上面的get請(qǐng)求方法為例
public interface BlueService {
@GET("book/search")
Call<BookSearchResponse> getSearchBooks(@QueryMap Map<String, String> options);
}
調(diào)用的時(shí)候?qū)⑺械膮?shù)集合在統(tǒng)一的map中即可
Map<String, String> options = new HashMap<>();
map.put("q", "小王子");
map.put("tag", null);
map.put("start", "0");
map.put("count", "3");
Call<BookSearchResponse> call = mBlueService.getSearchBooks(options);
Query集合
假如你需要添加相同Key值,但是value卻有多個(gè)的情況恋博,一種方式是添加多個(gè)@Query參數(shù)齐佳,還有一種簡(jiǎn)便的方式是將所有的value放置在列表中,然后在同一個(gè)@Query下完成添加债沮,實(shí)例代碼如下:
public interface BlueService {
@GET("book/search")
Call<BookSearchResponse> getSearchBooks(@Query("q") List<String> name);
}
最后得到的url地址為
https://api.douban.com/v2/book/search?q=leadership&q=beyond%20feelings
Query非必填
如果請(qǐng)求參數(shù)為非必填炼吴,也就是說(shuō)即使不傳該參數(shù),服務(wù)端也可以正常解析疫衩,那么如何實(shí)現(xiàn)呢硅蹦?
其實(shí)也很簡(jiǎn)單,請(qǐng)求方法定義處還是需要完整的Query注解闷煤,某次請(qǐng)求如果不需要傳該參數(shù)的話童芹,只需填充null即可。
針對(duì)文章開(kāi)頭提到的get的請(qǐng)求鲤拿,加入按以下方式調(diào)用
Call<BookSearchResponse> call = mBlueService.getSearchBooks("小王子", null, 0, 3);
那么得到的url地址為
https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&start=0&count=3
@Path
如果請(qǐng)求的相對(duì)地址也是需要調(diào)用方傳遞假褪,那么可以使用@Path注解,示例代碼如下:
@GET("book/{id}")
Call<BookResponse> getBook(@Path("id") String id);
業(yè)務(wù)方想要在地址后面拼接書(shū)籍id近顷,那么通過(guò)Path注解可以在具體的調(diào)用場(chǎng)景中動(dòng)態(tài)傳遞生音,具體的調(diào)用方式如下:
Call<BookResponse> call = mBlueService.getBook("1003078");
此時(shí)的url地址為
https://api.douban.com/v2/book/1003078
@Path可以用于任何請(qǐng)求方式,包括Post窒升,Put缀遍,Delete等等
Post請(qǐng)求
@field
Post請(qǐng)求需要把請(qǐng)求參數(shù)放置在請(qǐng)求體中,而非拼接在url后面饱须,先來(lái)看一個(gè)簡(jiǎn)單的例子
@FormUrlEncoded
@POST("book/reviews")
Call<String> addReviews(@Field("book") String bookId,
@Field("title") String title,
@Field("content") String content,
@Field("rating") String rating);
這里有幾點(diǎn)需要說(shuō)明的
@FormUrlEncoded將會(huì)自動(dòng)將請(qǐng)求參數(shù)的類型調(diào)整為application/x-www-form-urlencoded瑟由,假如content傳遞的參數(shù)為Good Luck,那么最后得到的請(qǐng)求體就是content=Good+Luck
FormUrlEncoded不能用于Get請(qǐng)求
@Field注解將每一個(gè)請(qǐng)求參數(shù)都存放至請(qǐng)求體中,還可以添加encoded參數(shù)歹苦,該參數(shù)為boolean型,具體的用法為
@Field(value = "book", encoded = true) String book
encoded參數(shù)為true的話督怜,key-value-pair將會(huì)被編碼殴瘦,即將中文和特殊字符進(jìn)行編碼轉(zhuǎn)換
@FieldMap
上述Post請(qǐng)求有4個(gè)請(qǐng)求參數(shù),假如說(shuō)有更多的請(qǐng)求參數(shù)号杠,那么通過(guò)一個(gè)一個(gè)的參數(shù)傳遞就顯得很麻煩而且容易出錯(cuò)蚪腋,這個(gè)時(shí)候就可以用FieldMap
@FormUrlEncoded
@POST("book/reviews")
Call<String> addReviews(@FieldMap Map<String, String> fields);
@Body
如果Post請(qǐng)求參數(shù)有多個(gè),那么統(tǒng)一封裝到類中應(yīng)該會(huì)更好姨蟋,這樣維護(hù)起來(lái)會(huì)非常方便
@FormUrlEncoded
@POST("book/reviews")
Call<String> addReviews(@Body Reviews reviews);
public class Reviews {
public String book;
public String title;
public String content;
public String rating;
}
其他請(qǐng)求方式:除了Get和Post請(qǐng)求屉凯,Http請(qǐng)求還包括Put,Delete等等,用法和Post相似眼溶。
上傳文件處理
上傳因?yàn)樾枰玫組ultipart悠砚,所以需要單獨(dú)拿出來(lái)介紹,先看一個(gè)具體上傳的例子
新建一個(gè)用于定義上傳方法interface
public interface FileUploadService {
// 上傳單個(gè)文件
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(
@Part("description") RequestBody description,
@Part MultipartBody.Part file);
// 上傳多個(gè)文件
@Multipart
@POST("upload")
Call<ResponseBody> uploadMultipleFiles(
@Part("description") RequestBody description,
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
在Activity和Fragment中實(shí)現(xiàn)兩個(gè)工具方法
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
@NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
}
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = FileUtils.getFile(this, fileUri);
// 為file建立RequestBody實(shí)例
RequestBody requestFile = RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part借助文件名完成最終的上傳
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
上傳文件邏輯處理
Uri file1Uri = ... // 從文件選擇器或者攝像頭中獲取
Uri file2Uri = ...
// 創(chuàng)建上傳的service實(shí)例
FileUploadService service =ServiceGenerator.createService(FileUploadService.class);
// 創(chuàng)建文件的part (photo, video, ...)
MultipartBody.Part body1 = prepareFilePart("video", file1Uri);
MultipartBody.Part body2 = prepareFilePart("thumbnail", file2Uri);
// 添加其他的part
RequestBody description = createPartFromString("hello, this is description speaking");
// 最后執(zhí)行異步請(qǐng)求操作
Call<ResponseBody> call = service.uploadMultipleFiles(description, body1, body2);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
其他必知的事項(xiàng)
添加header
Retrofit提供了兩個(gè)方式定義Http請(qǐng)求頭參數(shù):靜態(tài)方法和動(dòng)態(tài)方法堂飞,靜態(tài)方法不能隨不同的請(qǐng)求進(jìn)行變化灌旧,頭部信息在初始化的時(shí)候就固定了。而動(dòng)態(tài)方法則必須為每個(gè)請(qǐng)求都要單獨(dú)設(shè)置绰筛。
靜態(tài)方法
public interface BlueService {
@Headers("Cache-Control: max-age=640000")
@GET("book/search")
Call<BookSearchResponse> getSearchBooks(@Query("q") String name,
@Query("tag") String tag,
@Query("start") int start,
@Query("count") int count);
}
當(dāng)然你想添加多個(gè)header參數(shù)也是可以的枢泰,寫(xiě)法也很簡(jiǎn)單
public interface BlueService {
@Headers({"Accept: application/vnd.yourapi.v1.full+json","User-Agent:Your-App-Name"
})
@GET("book/search")
Call<BookSearchResponse> getSearchBooks(@Query("q") String name,
@Query("tag") String tag,
@Query("start") int start,
@Query("count") int count);
}
此外也可以通過(guò)Interceptor來(lái)定義靜態(tài)請(qǐng)求頭
public class RequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
添加header參數(shù)Request提供了兩個(gè)方法,一個(gè)是header(key, value)铝噩,另一個(gè)是.addHeader(key, value)衡蚂,兩者的區(qū)別是,header()如果有重名的將會(huì)覆蓋骏庸,而addHeader()允許相同key值的header存在毛甲,然后在OkHttp創(chuàng)建Client實(shí)例時(shí),添加RequestInterceptor即可
private static OkHttpClient getNewClient(){
return new OkHttpClient.Builder()
.addInterceptor(new RequestInterceptor())
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
}
動(dòng)態(tài)方法
public interface BlueService {
@GET("book/search")
Call<BookSearchResponse> getSearchBooks(@Header("Content-Range") String contentRange,
@Query("q") String name, @Query("tag") String tag,
@Query("start") int start, @Query("count") int count);
}
網(wǎng)絡(luò)請(qǐng)求日志
調(diào)試網(wǎng)絡(luò)請(qǐng)求的時(shí)候經(jīng)常需要關(guān)注一下請(qǐng)求參數(shù)和返回值敞恋,以便判斷和定位問(wèn)題出在哪里丽啡,Retrofit官方提供了一個(gè)很方便查看日志的Interceptor,你可以控制你需要的打印信息類型硬猫,使用方法也很簡(jiǎn)單补箍。
首先需要在build.gradle文件中引入logging-interceptor
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
同上面提到的CustomInterceptor和RequestInterceptor一樣,添加到OkHttpClient創(chuàng)建處即可啸蜜,完整的示例代碼如下:
private static OkHttpClient getNewClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.addInterceptor(new CustomInterceptor())
.addInterceptor(logging)
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
}
HttpLoggingInterceptor提供了4中控制打印信息類型的等級(jí)坑雅,分別是NONE,BASIC衬横,HEADERS裹粤,BODY,接下來(lái)分別來(lái)說(shuō)一下相應(yīng)的打印信息類型蜂林。
- NONE
沒(méi)有任何日志信息 - Basic
打印請(qǐng)求類型遥诉,URL拇泣,請(qǐng)求體大小,返回值狀態(tài)以及返回值的大小
D/HttpLoggingInterceptor$Logger: --> POST /upload HTTP/1.1 (277-byte body)
D/HttpLoggingInterceptor$Logger: <-- HTTP/1.1 200 OK (543ms, -1-byte body)
- Headers
打印返回請(qǐng)求和返回值的頭部信息矮锈,請(qǐng)求類型霉翔,URL以及返回值狀態(tài)碼
<-- 200 OK https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&start=0&count=3&token=tokenValue (3787ms)
D/OkHttp: Date: Sat, 06 Aug 2016 14:26:03 GMT
D/OkHttp: Content-Type: application/json; charset=utf-8
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Connection: keep-alive
D/OkHttp: Keep-Alive: timeout=30
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: Expires: Sun, 1 Jan 2006 01:00:00 GMT
D/OkHttp: Pragma: no-cache
D/OkHttp: Cache-Control: must-revalidate, no-cache, private
D/OkHttp: Set-Cookie: bid=D6UtQR5N9I4; Expires=Sun, 06-Aug-17 14:26:03 GMT; Domain=.douban.com; Path=/
D/OkHttp: X-DOUBAN-NEWBID: D6UtQR5N9I4
D/OkHttp: X-DAE-Node: dis17
D/OkHttp: X-DAE-App: book
D/OkHttp: Server: dae
D/OkHttp: <-- END HTTP
- Body
打印請(qǐng)求和返回值的頭部和body信息
<-- 200 OK https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&tag=&start=0&count=3&token=tokenValue (3583ms)
D/OkHttp: Connection: keep-alive
D/OkHttp: Date: Sat, 06 Aug 2016 14:29:11 GMT
D/OkHttp: Keep-Alive: timeout=30
D/OkHttp: Content-Type: application/json; charset=utf-8
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: Expires: Sun, 1 Jan 2006 01:00:00 GMT
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Pragma: no-cache
D/OkHttp: Connection: keep-alive
D/OkHttp: Cache-Control: must-revalidate, no-cache, private
D/OkHttp: Keep-Alive: timeout=30
D/OkHttp: Set-Cookie: bid=ESnahto1_Os; Expires=Sun, 06-Aug-17 14:29:11 GMT; Domain=.douban.com; Path=/
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: X-DOUBAN-NEWBID: ESnahto1_Os
D/OkHttp: Expires: Sun, 1 Jan 2006 01:00:00 GMT
D/OkHttp: X-DAE-Node: dis5
D/OkHttp: Pragma: no-cache
D/OkHttp: X-DAE-App: book
D/OkHttp: Cache-Control: must-revalidate, no-cache, private
D/OkHttp: Server: dae
D/OkHttp: Set-Cookie: bid=5qefVyUZ3KU; Expires=Sun, 06-Aug-17 14:29:11 GMT; Domain=.douban.com; Path=/
D/OkHttp: X-DOUBAN-NEWBID: 5qefVyUZ3KU
D/OkHttp: X-DAE-Node: dis17
D/OkHttp: X-DAE-App: book
D/OkHttp: Server: dae
D/OkHttp: {"count":3,"start":0,"total":778,"books":[{"rating":{"max":10,"numRaters":202900,"average":"9.0","min":0},"subtitle":"","author":["[法] 圣埃克蘇佩里"],"pubdate":"2003-8","tags":[{"count":49322,"name":"小王子","title":"小王子"},{"count":41381,"name":"童話","title":"童話"},{"count":19773,"name":"圣鞍浚克蘇佩里","title":"圣罢洌克蘇佩里"}
D/OkHttp: <-- END HTTP (13758-byte body)
為某個(gè)請(qǐng)求設(shè)置完整的URL
假如說(shuō)你的某一個(gè)請(qǐng)求不是以base_url開(kāi)頭該怎么辦呢?別著急瀑凝,辦法很簡(jiǎn)單序芦,看下面這個(gè)例子你就懂了
public interface BlueService {
@GET
public Call<ResponseBody> profilePicture(@Url String url);
}
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/");
.build();
BlueService service = retrofit.create(BlueService.class);
service.profilePicture("https://s3.amazon.com/profile-picture/path");
直接用@Url注解的方式傳遞完整的url地址即可。
取消請(qǐng)求
Call提供了cancel方法可以取消請(qǐng)求粤咪,前提是該請(qǐng)求還沒(méi)有執(zhí)行
String fileUrl = "http://futurestud.io/test.mp4";
Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "request success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (call.isCanceled()) {
Log.e(TAG, "request was cancelled");
} else {
Log.e(TAG, "other larger issue, i.e. no network connection?");
}
}
});
// 觸發(fā)某個(gè)動(dòng)作谚中,例如用戶點(diǎn)擊了取消請(qǐng)求的按鈕
call.cancel();