Android網(wǎng)絡(luò)請求框架Retrofit詳解
介紹:
Retrofit 是Square公司開發(fā)的一款針對Android網(wǎng)絡(luò)請求的框架,Retrofit2底層基于OkHttp實現(xiàn)的,OkHttp現(xiàn)在已經(jīng)得到Google官方認可,大量的app都采用OkHttp做網(wǎng)絡(luò)請求。本文使用Retrofit2.0.0版本進行實例演示。
使用Retrofit可以進行GET,POST,PUT,DELETE等請求方式。
同步請求:需要在子線程中完成,會阻塞主線程。
Response response = call.execute().body();
異步請求:請求結(jié)果在主線程中回調(diào),可以在onResponse()回調(diào)方法進行更新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' //這兩個jar版本要一致,否則會有沖突
(2) 創(chuàng)建業(yè)務(wù)請求接口,具體代碼如下
/**
* 創(chuàng)建業(yè)務(wù)請求接口
*/
public interface IUserService {
/**
* GET請求
*/
@GET("Servlet/UserServlet")
Call<User> getUser(@Query("email") String email);
/**
* POST請求
*/
@FormUrlEncoded
@POST("UserServlet")
Call<User> postUser(@Field("name") String name, @Field("email") String email);
}
解釋說明:
@GET注解表示GET請求,@Query表示請求參數(shù),將會以key=value(@Query注解參數(shù)名稱為key,調(diào)用傳進來的值為value)的方式拼接在url后面.
@POST注解表示POST請求,@FormUrlEncoded將會自動將請求參數(shù)的類型設(shè)置為application/x-www-form-urlencoded,@FormUrlEncoded注解不能用于Get請求。@Field注解將每一個請求參數(shù)都存放至請求體中,還可以添加encoded參數(shù),該參數(shù)為boolean型,具體的用法為:
@Field(value = "password", encoded = true) String pwd
encoded參數(shù)為true的話,key-value-pair將會被編碼,即將中文和特殊字符進行編碼轉(zhuǎn)換.
(3)創(chuàng)建Retrofit對象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IUserService iUserService = retrofit.create(IUserService.class);
解釋說明:
baseUrl()方法制定網(wǎng)絡(luò)請求的固定絕對地址,一般包括請求協(xié)議(如Http)、域名或IP地址、端口號。
創(chuàng)建Retrofit實例時,若沒有配置addConverterFactory(GsonConverterFactory.create())將會回調(diào)出JSON字符串,配置了將會回調(diào)實體對象。
支持的JSON解析庫:
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)用請求方法,并得到Call實例
Call<ResponseBody> call = iUserService.getUser(xing-java@foxmail.com);
(5) 使用Call實例完成同步或異步請求
/**
* 發(fā)送GET請求
*/
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) {
}
});
}
請求方式:
(1)GET 請求:
GET 請求返回 JSON 字符串:

GET 請求返回實體對象:

(2) POST發(fā)送表單:
/**
* 發(fā)送POST請求
*/
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) {
}
});
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android基于BaseExpandableListAdapter實現(xiàn)的二級列表仿通話記錄功能詳解
這篇文章主要介紹了Android基于BaseExpandableListAdapter實現(xiàn)的二級列表仿通話記錄功能,結(jié)合具體實例形式分析了Android實現(xiàn)通話記錄功能的布局與功能相關(guān)操作技巧,需要的朋友可以參考下2017-07-07
Android AndBase框架使用封裝好的函數(shù)完成Http請求(三)
這篇文章主要介紹了Android AndBase框架使用封裝好的函數(shù)完成Http請求的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-03-03
Android Kotlin 基本數(shù)據(jù)類型詳解
Kotlin是一種靜態(tài)類型語言,適用于Android開發(fā),Kotlin的基本數(shù)據(jù)類型包括數(shù)值類型、字符類型、布爾類型和數(shù)組類型,本文介紹Android Kotlin 基本數(shù)據(jù)類型,感興趣的朋友一起看看吧2025-03-03
Android EditText監(jiān)聽回車鍵并處理兩次回調(diào)問題
這篇文章主要介紹了Android EditText監(jiān)聽回車鍵并處理兩次回調(diào)問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

