簡(jiǎn)介:
Retrofit是目前最流行的HTTP請(qǐng)求工具鄙皇。
使用方法
1.添加依賴:
compile 'com.squareup.retrofit2:retrofit:2.2.0'
2.具體操作步驟:
現(xiàn)假設(shè)要訪問網(wǎng)頁:https://androidtutorialpoint.com/api/RetrofitAndroidObjectResponse
倦逐,其返回的JSON數(shù)據(jù)如下所示:
{
"StudentId":"1",
"StudentName":"Rahul",
"StudentMarks":"83"
}
則使用Retrofit獲取該網(wǎng)頁返回的JSON數(shù)據(jù)的具體步驟如下:
- 定義一個(gè)接口冈欢,Retrofit會(huì)將該接口轉(zhuǎn)換成為HTTP請(qǐng)求
public interface StudentRequestService{
@GET("api/RetrofitAndroidObjectResponse")
Call<ResponseBody> obtainStudentInfo();
}
- 發(fā)起HTTP請(qǐng)求霞幅,獲取結(jié)果
//創(chuàng)建一個(gè)Retrofit客戶端
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.androidtutorialpoint.com/")
.build();
//得到一個(gè)StudentRequestService代理對(duì)象
StudentRequestService studentRequestServiceProxy = retrofit.create(StudentRequestService.class);
//生成一個(gè)HTTP請(qǐng)求
Call<ResponseBody> studentInfo = studentRequestServiceProxy.obtainStudentInfo();
//最后民珍,就可以通過studentInfo對(duì)象獲取WebServer內(nèi)容
//此處有兩種請(qǐng)求方法:同步調(diào)用桶略,異步調(diào)用
//這里使用的是異步調(diào)用方法
studentInfo.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);
}
});
** result: **
Retrofit訪問WebServer返回的結(jié)果
進(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)換术羔。
由于我們需要獲取的是Student的信息赢赊,那么我們可以創(chuàng)建一個(gè)Student的POJO類,
然后通過GsonConverter進(jìn)行轉(zhuǎn)換级历,就可以避免手動(dòng)解析JSON了释移,具體做法如下:
- 添加Gson依賴:
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
- 創(chuàng)建POJO類:
通過jsonschema2pojo這個(gè)網(wǎng)站可以快捷方便生成所需Bean類。
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Student {
@SerializedName("StudentId")
@Expose
private String studentId;
@SerializedName("StudentName")
@Expose
private String studentName;
@SerializedName("StudentMarks")
@Expose
private String studentMarks;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentMarks() {
return studentMarks;
}
public void setStudentMarks(String studentMarks) {
this.studentMarks = studentMarks;
}
@Override
public String toString() {
return String.format("id:%s\nname:%s\nmarks:%s", studentId, studentName, studentMarks);
}
}```
* 定義一個(gè)接口寥殖,Retrofit會(huì)將該接口轉(zhuǎn)換成為HTTP請(qǐng)求
```java
public interface StudentRequestService{
@GET("api/RetrofitAndroidObjectResponse")
Call<Student> obtainStudentInfo();
}
- 發(fā)起HTTP請(qǐng)求玩讳,獲取結(jié)果
//創(chuàng)建一個(gè)Retrofit客戶端
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.androidtutorialpoint.com/")
//增加Gson轉(zhuǎn)換
.addConverterFactory(GsonConverterFactory.create())
.build();
//得到一個(gè)StudentRequestService代理對(duì)象
Interfaces.StudentRequestService studentRequestServiceProxy = retrofit.create(Interfaces.StudentRequestService.class);
//生成一個(gè)HTTP請(qǐng)求
Call<Student> studentInfo = studentRequestServiceProxy.obtainStudentInfo();
studentInfo.enqueue(new Callback<Student>() {
@Override
public void onResponse(Call<Student> call, Response<Student> response) {
Student student = response.body();
Log.i(TAG, student.toString());
}
@Override
public void onFailure(Call<Student> call, Throwable t) {
Log.i(TAG, "onFailure: " + t);
}
});
** result: **
resultGson.png
** 最后的最后,千萬不要忘記在AndroidManifest.xml中加入權(quán)限:**
<uses-permission android:name="android.permission.INTERNET" />