Retrofit可以理解為OkHttp的加強(qiáng)版,也是一個(gè)網(wǎng)絡(luò)加載框架,底層是使用OkHttp封裝的,網(wǎng)絡(luò)請(qǐng)求工作本質(zhì)是OkHttp完成,而Retrofit負(fù)責(zé)網(wǎng)絡(luò)請(qǐng)求接口的封裝。
Retrofit2的優(yōu)點(diǎn)
1.超級(jí)解耦
2.可以配置不同的HttpClient來(lái)實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求
3.支持同步、異步和RxJava
4.可以配置不同的反序列化工具來(lái)解析數(shù)據(jù):如json、xml
5.請(qǐng)求速度快,使用非常方便靈活
Retrofit2配置
implementation 'com.squareup.retrofit2:retrofit:2.5.0' //Retrofit依賴
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'//可選依賴,解析json字符所用
Retrofit2的使用步驟
1.定義接口類(封裝URL地址和數(shù)據(jù)請(qǐng)求)
2.實(shí)例化Retrofit
3.通過(guò)Retrofit實(shí)例創(chuàng)建接口服務(wù)對(duì)象
4.接口服務(wù)對(duì)象調(diào)用接口中的方法,獲取Call對(duì)象
5.Call對(duì)象執(zhí)行請(qǐng)求(異步,同步請(qǐng)求)
get請(qǐng)求
String baseURL = "https://www.xxxxx.com/abc/"; //從頭開(kāi)始到任意一個(gè)斜杠結(jié)束
public interface MyServer{
@GET("json?cid=9")
Call<ResponseBody> getData();
}
//獲取Retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL).build();
//通過(guò)Retrofit獲取接口服務(wù)對(duì)象
MyServer server = retrofit.create(MyServer.class);
//接口對(duì)象調(diào)用其方法獲取call對(duì)象
Call<ResponseBody> data = server.getData();
//call執(zhí)行請(qǐng)求
data.enqueue(new Callback<ResponseBody>(){
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response){
try{
String json = response.body().string();
}catch(Exception e){}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t){
}
});
post請(qǐng)求
String URL = "https://www.xxxx.com/abc/";
public interface MyServer{
//POST("search?")和POST("search") 相同;
//@Field("key") String value post請(qǐng)求用來(lái)提交參數(shù)的
//@FormUrlEncoded post請(qǐng)求提交form表單的時(shí)候如果有參數(shù),需要填加這個(gè)注解,用來(lái)將提交的參數(shù)編碼,post請(qǐng)求不提交參數(shù),不要加
//@Field和@FieldMap一樣,@FieldMap只不過(guò)是把一個(gè)一個(gè)的參數(shù),合成一個(gè)map
@POST("search?")
@FormUrlEncoded
Call<ResponseBody> postData1(@Field("key") String appkey, @Field("name") String appname);
@POST("search")
@FormUrlEncoded
Call<ResponseBody> postData2(@FieldMap Map<String, Object> map);
}
private void initPostEnqueue(){
//1.創(chuàng)建Retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder().baseUrl(URL).build();
//2.獲取接口服務(wù)對(duì)象
MyServer myServer = retrofit.create(MyServer.class);
//3.獲取Call對(duì)象
//方式一
Call<ResponseBody> call1 = myServer.postData1("123", "45666");
//方式二
Map<String, Object> map = new HashMap<>();
map.put("123", "4566");
//不用切換主線程了,因?yàn)镽etrofit幫我們切過(guò)了
//okHttpClient需要自己切換主線程
Call<ResponseBody> call = myServer.postData2(map);
//4.Call對(duì)象執(zhí)行請(qǐng)求
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);//默認(rèn)直接回調(diào)主線程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
Retrofit的注解

轉(zhuǎn)換器
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
Gson轉(zhuǎn)換器的使用:
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.xxx.com/abc/")
.addConverterFactory(GsonConverterFactory.create()).build();
創(chuàng)建一個(gè)實(shí)體類UserBean.
public interface GithubService{
@GET("users/{user}")
Call<UserBean> getUserString(@Path("user") String user);
}
GithubService service retrofit.create(GithubService.class);
Call<UserBean> call = service.getUserString("aaaaa");
call.enqueue(new Callback<UserBean>(){
@Override
public void onResponse(Call<UserBean> call, Response<UserBean> response){
UserBean userBean = response.body();
}
@Override
public void onFailure(Call<GithubUserBean> call, Throwable t) {
}
});
注意:接口中返回的類型Call的泛型要么是ResponseBody要么是實(shí)體類,不支持其他類型。
OkHttp、Volley、Retrofit的對(duì)比
1.Volley VS OkHttp
Volley的優(yōu)勢(shì)在于封裝更好,而OkHttp需要足夠的能力再進(jìn)行一次封裝。
而OkHttp的優(yōu)勢(shì)在于性能更高,因?yàn)榛贜IO和Okio,性能上比Volley更快。
從硬盤讀取數(shù)據(jù),第一種方式就是程序一直等,數(shù)據(jù)讀完后才能繼續(xù)操作,這種是最簡(jiǎn)單的也叫阻塞式 IO,還有一種就是你讀你的,我程序接著往下執(zhí)行,等數(shù)據(jù)處理完你再來(lái)通知我,然后再處理回調(diào)。而第二種就是 NIO 的方式,非阻塞式。
所以 NIO 當(dāng)然要比 IO 的性能要好了, 而 Okio 是 Square 公司基于 IO 和 NIO 基礎(chǔ)上做的一個(gè)更簡(jiǎn)單、高效處理數(shù)據(jù)流的一個(gè)庫(kù)。
Volley內(nèi)部同樣支持使用OkHttp,本身Volley封裝也更容易,擴(kuò)展性更好。
2.OkHttp VS Retrofit
Retrofit基于OkHttp而做的封裝,首選Retrofit。
3.Volley VS Retrofit
封裝都不錯(cuò),但是Retrofit解耦的更徹底。默認(rèn)使用OkHttp性能上比Volley更好,如果項(xiàng)目采用的RxJava,那更推薦Retrofit。
都掌握的情況下優(yōu)先使用Retrofit,如果不是很了解Retrofit,優(yōu)先使用Volley。