Retrofit是目前最流行的HTTP請(qǐng)求工具迟杂。
使用方法:
1.添加依賴:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
2.定義一個(gè)接口,Retrofit會(huì)將該接口轉(zhuǎn)換成為HTTP請(qǐng)求
public interface APIService{
@GET("api/getUser")
Call<ResponseBody> getUserInfo();
}
3.發(fā)起HTTP請(qǐng)求胜臊,獲取結(jié)果
//創(chuàng)建一個(gè)Retrofit客戶端
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("XXXXXXXXX")
.build();
//得到一個(gè)APIService代理對(duì)象
APIService apiService = retrofit.create(APIService.class);
//生成一個(gè)HTTP請(qǐng)求
Call<ResponseBody> userInfo = apiService.getUserInfo();
//最后馍资,就可以通過studentInfo對(duì)象獲取WebServer內(nèi)容
//此處有兩種請(qǐng)求方法:同步調(diào)用膀捷,異步調(diào)用
//這里使用的是異步調(diào)用方法
userInfo.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i(TAG,response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i(TAG, "onFailure: "+t);
}
});
進(jìn)階
上面方法獲取到的是JSON數(shù)據(jù),還要經(jīng)過手動(dòng)進(jìn)一步解析才能獲取所需內(nèi)容拿穴,
而Retrofit默認(rèn)只能解碼HTTP bodies到 OkHttp's ResponseBody類型泣洞,要想使
Retrofit支持其他類型轉(zhuǎn)換,必須通過Converters(數(shù)據(jù)轉(zhuǎn)換器)轉(zhuǎn)換默色。
1.添加Gson依賴:
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
2.創(chuàng)建User類
public class User {
@SerializedName("userId")
@Expose
private String userId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private int age;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return String.format("id:%s\nname:%s\nage:%d", userId, name, age);
}
}
3.定義接口修改
public interface APIService{
@GET("api/getUser")
Call<User> getUserInfo();
}
4.發(fā)起HTTP請(qǐng)求修改
//創(chuàng)建一個(gè)Retrofit客戶端
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("XXXXXXXXXXX")
//增加Gson轉(zhuǎn)換
.addConverterFactory(GsonConverterFactory.create())
.build();
//得到一個(gè)APIService代理對(duì)象
APIService apiService = retrofit.create(APIService.class);
//生成一個(gè)HTTP請(qǐng)求
Call<User> userInfo = apiService.getUserInfo();
userInfo.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
Log.i(TAG, user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.i(TAG, "onFailure: " + t);
}
});