Android網(wǎng)絡(luò)請(qǐng)求框架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)求。本文使用Retrofit2.0.0版本進(jìn)行實(shí)例演示。
使用Retrofit可以進(jìn)行GET,POST,PUT,DELETE等請(qǐng)求方式。
同步請(qǐng)求:需要在子線程中完成,會(huì)阻塞主線程。
Response response = call.execute().body();
異步請(qǐng)求:請(qǐng)求結(jié)果在主線程中回調(diào),可以在onResponse()回調(diào)方法進(jìn)行更新UI。
call.enqueue(Callback callback)
使用步驟:
(1) 創(chuàng)建工程,添加jar:
compile 'com.squareup.retrofit2:retrofit:2.0.0' compile 'com.squareup.retrofit2:converter-gson:2.0.0' //這兩個(gè)jar版本要一致,否則會(huì)有沖突
(2) 創(chuàng)建業(yè)務(wù)請(qǐng)求接口,具體代碼如下
/**
* 創(chuàng)建業(yè)務(wù)請(qǐng)求接口
*/
public interface IUserService {
/**
* GET請(qǐng)求
*/
@GET("Servlet/UserServlet")
Call<User> getUser(@Query("email") String email);
/**
* POST請(qǐng)求
*/
@FormUrlEncoded
@POST("UserServlet")
Call<User> postUser(@Field("name") String name, @Field("email") String email);
}
解釋說(shuō)明:
@GET注解表示GET請(qǐng)求,@Query表示請(qǐng)求參數(shù),將會(huì)以key=value(@Query注解參數(shù)名稱為key,調(diào)用傳進(jìn)來(lái)的值為value)的方式拼接在url后面.
@POST注解表示POST請(qǐng)求,@FormUrlEncoded將會(huì)自動(dòng)將請(qǐng)求參數(shù)的類(lèi)型設(shè)置為application/x-www-form-urlencoded,@FormUrlEncoded注解不能用于Get請(qǐng)求。@Field注解將每一個(gè)請(qǐng)求參數(shù)都存放至請(qǐng)求體中,還可以添加encoded參數(shù),該參數(shù)為boolean型,具體的用法為:
@Field(value = "password", encoded = true) String pwd
encoded參數(shù)為true的話,key-value-pair將會(huì)被編碼,即將中文和特殊字符進(jìn)行編碼轉(zhuǎn)換.
(3)創(chuàng)建Retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IUserService iUserService = retrofit.create(IUserService.class);
解釋說(shuō)明:
baseUrl()方法制定網(wǎng)絡(luò)請(qǐng)求的固定絕對(duì)地址,一般包括請(qǐng)求協(xié)議(如Http)、域名或IP地址、端口號(hào)。
創(chuàng)建Retrofit實(shí)例時(shí),若沒(méi)有配置addConverterFactory(GsonConverterFactory.create())將會(huì)回調(diào)出JSON字符串,配置了將會(huì)回調(diào)實(shí)體對(duì)象。
支持的JSON解析庫(kù):
Gson: compile ‘com.squareup.retrofit2:converter-gson:2.0.1'
Jackson: compile ‘com.squareup.retrofit2:converter-jackson:2.0.1'
Moshi: compile ‘com.squareup.retrofit2:converter-moshi:2.0.1'
Protobuf: compile ‘com.squareup.retrofit2:converter-protobuf:2.0.1'
Wire: compile ‘com.squareup.retrofit2:converter-wire:2.0.1'
Simple XML: compile ‘com.squareup.retrofit2:converter-simplexml:2.0.1'
Scalars (primitives, boxed, and String): compile ‘com.squareup.retrofit2:converter-scalars:2.0.1'
(4) 調(diào)用請(qǐng)求方法,并得到Call實(shí)例
Call<ResponseBody> call = iUserService.getUser(xing-java@foxmail.com);
(5) 使用Call實(shí)例完成同步或異步請(qǐng)求
/**
* 發(fā)送GET請(qǐng)求
*/
private void getRequest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IUserService iUserService = retrofit.create(IUserService.class);
Call<User> call = iUserService.getUser("xing-java@foxmail.com");
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Log.i("MainActivity", "response = " + response);
User user = response.body();
resTxtView.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
請(qǐng)求方式:
(1)GET 請(qǐng)求:
GET 請(qǐng)求返回 JSON 字符串:

GET 請(qǐng)求返回實(shí)體對(duì)象:

(2) POST發(fā)送表單:
/**
* 發(fā)送POST請(qǐng)求
*/
private void postRequest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IUserService iUserService = retrofit.create(IUserService.class);
Call<User> call = iUserService.postUser("star.tao", "xing-java@foxmail.com");
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
}
@Override
public void onFailure(Call<User> call, Throwable throwable) {
}
});
服務(wù)端接收到的結(jié)果:

(3)文件上傳:
private void uploadFile() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constant.BASE_URL)
.build();
IUserService iUserService = retrofit.create(IUserService.class);
File file = new File("/sdcard/s.png");
RequestBody fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("upload_file", file.getName(), fileRequestBody);
String desc = "this is file description";
RequestBody descRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), desc);
Call<ResponseBody> call = iUserService.uploadFile(descRequestBody, multipartBody);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.i("debug", "upload success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android應(yīng)用開(kāi)發(fā)之代碼混淆
Android項(xiàng)目中的混淆很easy,之所以寫(xiě)這篇總結(jié)是由于近期發(fā)現(xiàn)公司的代碼居然沒(méi)有混淆,反編譯后代碼隨手可得。很震驚。2014-07-07
詳解Android的內(nèi)存優(yōu)化--LruCache
LruCache是基于Lru算法實(shí)現(xiàn)的一種緩存機(jī)制。本文對(duì)LruCache的概念和實(shí)現(xiàn)原理進(jìn)行介紹,通過(guò)實(shí)例分析和使用介紹,讓大家更好的了解LruCache,下面跟著小編一起來(lái)看下吧2016-12-12
Android編程實(shí)現(xiàn)系統(tǒng)重啟與關(guān)機(jī)的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)系統(tǒng)重啟與關(guān)機(jī)的方法,較為詳細(xì)的分析了Android運(yùn)行原理與源碼剖析,講述了Android編程實(shí)現(xiàn)系統(tǒng)重啟與關(guān)機(jī)的相關(guān)技巧與注意事項(xiàng),需要的朋友可以參考下2016-02-02
Java操作FreeMarker模板引擎的基本用法示例小結(jié)
這篇文章主要介紹了Java操作FreeMarker模板引擎的基本用法示例小結(jié),FreeMarker本身由Java寫(xiě)成,用模板來(lái)生成文本輸出,需要的朋友可以參考下2016-02-02
Android XRecyclerView實(shí)現(xiàn)多條目加載
這篇文章主要為大家詳細(xì)介紹了Android XRecyclerView實(shí)現(xiàn)多條目加載效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
Android 組合控件實(shí)現(xiàn)布局的復(fù)用的方法
本篇文章主要介紹了Android 組合控件實(shí)現(xiàn)布局的復(fù)用的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
Android實(shí)現(xiàn)底部導(dǎo)航欄功能(選項(xiàng)卡)
這篇文章主要介紹了Android實(shí)現(xiàn)底部導(dǎo)航欄功能,可以隨意切換不同的頁(yè)面,實(shí)現(xiàn)選項(xiàng)卡功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-12-12

