Retrofit 2.0基本使用方法

簡介:

Retrofit是目前最流行的HTTP請求工具。

使用方法

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ù)的具體步驟如下:

  • 定義一個接口,Retrofit會將該接口轉(zhuǎn)換成為HTTP請求
public interface StudentRequestService{
    @GET("api/RetrofitAndroidObjectResponse")
     Call<ResponseBody>  obtainStudentInfo();
}

  • 發(fā)起HTTP請求,獲取結(jié)果
//創(chuàng)建一個Retrofit客戶端
  Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("https://www.androidtutorialpoint.com/")
          .build();

  //得到一個StudentRequestService代理對象
  StudentRequestService studentRequestServiceProxy = retrofit.create(StudentRequestService.class);
//生成一個HTTP請求
  Call<ResponseBody> studentInfo = studentRequestServiceProxy.obtainStudentInfo();
  //最后,就可以通過studentInfo對象獲取WebServer內(nèi)容
  //此處有兩種請求方法:同步調(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)過手動進(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)建一個Student的POJO類,
然后通過GsonConverter進(jìn)行轉(zhuǎn)換,就可以避免手動解析JSON了,具體做法如下:

  • 添加Gson依賴:
 compile 'com.squareup.retrofit2:converter-gson:2.2.0'
  • 創(chuàng)建POJO類:
    通過jsonschema2pojo這個網(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);
    }
}```

* 定義一個接口,Retrofit會將該接口轉(zhuǎn)換成為HTTP請求

```java
public interface StudentRequestService{
    @GET("api/RetrofitAndroidObjectResponse")
     Call<Student>  obtainStudentInfo();
}

  • 發(fā)起HTTP請求,獲取結(jié)果

  //創(chuàng)建一個Retrofit客戶端
  Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("https://www.androidtutorialpoint.com/")
          //增加Gson轉(zhuǎn)換
          .addConverterFactory(GsonConverterFactory.create())
          .build();

  //得到一個StudentRequestService代理對象
  Interfaces.StudentRequestService studentRequestServiceProxy = retrofit.create(Interfaces.StudentRequestService.class);
//生成一個HTTP請求
  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" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容