Retrofit2
1.Retrofit2概述
1,Retrofit框架是Square公司出品的目前非常流行的網(wǎng)絡(luò)框架.
效率高串慰,實現(xiàn)簡單裹纳,運用注解和動態(tài)代理.
極大簡化了網(wǎng)絡(luò)請求的繁瑣步驟赛不,非常適合REST ful網(wǎng)絡(luò)請求.
目前Retofit版本是2
2,Retrofit其實我們可以理解為OkHttp的加強版碑宴。
它也是一個網(wǎng)絡(luò)加載框架裆甩。底層是使用OKHttp封裝的之斯。
準確來說,網(wǎng)絡(luò)請求的工作本質(zhì)上是OkHttp完成,而 Retrofit 僅負責網(wǎng)絡(luò)請求接口的封裝庞萍。
它的一個特點是包含了特別多注解拧烦,方便簡化你的代碼量。
并且還支持很多的開源庫(著名例子:Retrofit + RxJava)
2.Retrofit2的好處
1钝计,超級解耦
解耦恋博?解什么耦?
我們在請求接口數(shù)據(jù)的時候私恬,API接口定義和API接口使用總是相互影
響债沮,什么傳參、回調(diào)等本鸣,耦合在一塊疫衩。有時候我們會考慮一下怎么封裝我們的代
碼讓這兩個東西不那么耦合,這個就是Retrofit的解耦目標荣德,也是它的最大的特點闷煤。
2,可以配置不同HttpClient來實現(xiàn)網(wǎng)絡(luò)請求涮瞻,如OkHttp鲤拿、HttpClient...
3,支持同步署咽、異步和RxJava
4近顷,可以配置不同的反序列化工具來解析數(shù)據(jù),如json宁否、xml...
5窒升,請求速度快,使用非常方便靈活
3.Retrofit2配置
1家淤,官網(wǎng):http://square.github.io/retrofit/
2异剥,依賴:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
3瑟由,OkHttp庫依賴
由于Retrofit是基于OkHttp絮重,所以還需要添加OkHttp庫依賴
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
4,添加網(wǎng)絡(luò)權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
4歹苦,Retrofit2的使用步驟
1青伤,定義接口(封裝URL地址和數(shù)據(jù)請求)
2,實例化Retrofit
3殴瘦,通過Retrofit實例創(chuàng)建接口服務(wù)對象
4狠角,接口服務(wù)對象調(diào)用接口中的方法,獲取Call對象
5蚪腋,Call對象執(zhí)行請求(異步丰歌、同步請求)
Retrofit2發(fā)送GET姨蟋、POST請求(異步、同步)
1.Retrofit2發(fā)送GET
//主機地址
String URL = "http://api.shujuzhihui.cn/api/news/";//必須以反斜杠結(jié)尾
//接口服務(wù)
public interface MyServer {
//GET
@GET("categories?appKey=908ca46881994ffaa6ca20b31755b675")
Call<ResponseBody> getData1();
@GET("categories?")
Call<ResponseBody> getData2(@Query("appKey") String appkey);
@GET("categories?")
Call<ResponseBody> getData3(@QueryMap Map<String,Object> map);
}
//Get異步
private void initGetEnqueue() {
//1.創(chuàng)建Retrofit對象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.獲取MyServer接口服務(wù)對象
MyServer myServer = retrofit.create(MyServer.class);
//3.獲取Call對象
//方式一
Call<ResponseBody> call1 = myServer.getData1();
//方式二
Call<ResponseBody> call2 = myServer.getData2("908ca46881994ffaa6ca20b31755b675");
//方式三
Map<String,Object> map = new HashMap<>();
map.put("appKey","908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call = myServer.getData3(map);
//4.Call對象執(zhí)行請求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默認直接回調(diào)主線程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
//GET同步
private void initGetExecute() {
//1.創(chuàng)建Retrofit對象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.獲取MyServer接口服務(wù)對象
MyServer myServer = retrofit.create(MyServer.class);
//3.獲取Call對象
final Call<ResponseBody> call = myServer.getData1();
new Thread(){//子線程執(zhí)行
@Override
public void run() {
super.run();
try {
//4.Call對象執(zhí)行請求
Response<ResponseBody> response = call.execute();
final String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(result);//默認直接回調(diào)主線程
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
2.Retrofit2發(fā)送POST
String URL = "http://api.shujuzhihui.cn/api/news/";//必須以反斜杠結(jié)尾
public interface MyServer {
//POST("categories?") POST("categories")相同
@POST("categories?")
@FormUrlEncoded
Call<ResponseBody> postData1(@Field("appKey") String appKey);
@POST("categories")
@FormUrlEncoded
Call<ResponseBody> postData2(@FieldMap Map<String,Object> map);
}
//POST異步
private void initPostEnqueue() {
//1.創(chuàng)建Retrofit對象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.獲取MyServer接口服務(wù)對象
MyServer myServer = retrofit.create(MyServer.class);
//3.獲取Call對象
//方式一
Call<ResponseBody> call1 = myServer.postData1("908ca46881994ffaa6ca20b31755b675");
//方式二
Map<String,Object> map = new HashMap<>();
map.put("appKey","908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call = myServer.postData2(map);
//4.Call對象執(zhí)行請求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默認直接回調(diào)主線程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
Retrofit注解
注解代碼 請求格式
請求方式:
@GET GET請求
@POST POST請求
@DELETE DELETE請求
@HEAD HEAD請求
@OPTIONS OPTIONS請求
@PATCH PATCH請求
請求頭:
@Headers("K:V") 添加請求頭立帖,作用于方法
@Header("K") 添加請求頭眼溶,參數(shù)添加頭
@FormUrlEncoded 用表單數(shù)據(jù)提交,搭配參數(shù)使用
@Multipart 用文件上傳提交 multipart/form-data
請求參數(shù):
@Query 替代參數(shù)值晓勇,通常是結(jié)合get請求的
@QueryMap 替代參數(shù)值堂飞,通常是結(jié)合get請求的
@Field 替換參數(shù)值,是結(jié)合post請求的
@FieldMap 替換參數(shù)值绑咱,是結(jié)合post請求的
請求路徑:
@Path 替換路徑
@Url 路徑拼接
請求體:
@Body(RequestBody) 設(shè)置請求體绰筛,是結(jié)合post請求的
文件處理:
@Part Multipart.Part
@Part("key") RequestBody requestBody(單參)
@PartMap Map<String,RequestBody> requestBodyMap(多參)
@Body RequestBody requestBody(自定義參數(shù))
Retrofit2其他常用注解使用
String URL = "http://api.shujuzhihui.cn/api/news/";//必須以反斜杠結(jié)尾
public interface MyServer {
//Path
@GET("wages/{wageId}/detail")
Call<ResponseBody >getImgData(@Path("wageId") String wageId);
//Url
@GET
Call<ResponseBody >getImgData(@Url String url);
@GET
Call<ResponseBody >getImgData(@Url String url,@Query("appKey") String appkey);
//Json
@POST("categories")
@Headers("Content-Type:application/json")
Call<ResponseBody> getFormDataJson(@Body RequestBody requestBody);
//Form
@POST("categories")
@Headers("Content-Type:application/x-www-form-urlencoded")
Call<ResponseBody> getFormData1(@Body RequestBody requestBody);
//復用URL
@POST()
@Headers("Content-Type:application/x-www-form-urlencoded")
Call<ResponseBody> getFormData2(@Url String url,@Body RequestBody requestBody);
//通用
@POST()
Call<ResponseBody> getFormData3(@Url String url, @Body RequestBody requestBody, @Header("Content-Type") String contentType);
}
//RequestBody參數(shù)拼接
private void initPostBody() {
Retrofit.Builder builder = new Retrofit.Builder();
Retrofit retrofit = builder.baseUrl(MyServer.URL)
.build();
MyServer myServer = retrofit.create(MyServer.class);
//Json類型
String json1 = "{\n" + " \"appKey\": \"908ca46881994ffaa6ca20b31755b675\"\n" + "}";
RequestBody requestBody01 = RequestBody.create(MediaType.parse("application/json,charset-UTF-8"),json1);
Call<ResponseBody> call01 = myServer.getFormDataJson(requestBody01);
//String類型
//有參形式
RequestBody requestBody02 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"appKey=908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call02 = myServer.getFormData1(requestBody02);
//無參形式
RequestBody requestBody3 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"");
Call<ResponseBody> call03 = myServer.getFormData1(requestBody3);
//RequestBody (Form表單,鍵值對參數(shù)形式)
//方式一(requestBody)
FormBody requestBody = new FormBody.Builder()
.add("appKey","908ca46881994ffaa6ca20b31755b675")
.build();
Call<ResponseBody> call1 = myServer.getFormData1(requestBody);
//方式二(url+requestBody)
FormBody requestBody = new FormBody.Builder()
.add("appKey","908ca46881994ffaa6ca20b31755b675")
.build();
Call<ResponseBody> call2 = myServer.getFormData2("categories",requestBody);
//方式三(url+requestBody+header)
FormBody requestBody = new FormBody.Builder()
.add("appKey","908ca46881994ffaa6ca20b31755b675")
.build();
Call<ResponseBody> call3 = myServer.getFormData3("categories",requestBody,"application/x-www-form-urlencoded");
call3.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默認直接回調(diào)主線程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}