Retrofit使用教程(一)

Square公司開源了許多優秀的庫,Retrofit就是其中之一。

Retrofit是用來簡化APP訪問服務器API,如果你的服務器使用的使RESTAPI,那麼趕緊使用Retrofit吧。

官方的文檔是用GitHub的API說明使用過程的,有的童鞋可能從沒用過GitHub的API(比如我),爲了簡單易懂,這裏我使用一個查詢手機歸屬地的API來說明Retrofit的使用過程。

集成

目前我使用的是AndroidStudio,那麼在model的build.gradle文件中添加以下引用:

    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.jakewharton:butterknife:7.0.1'

說明:

  • Retrofit依賴於okhttp,所以需要集成okhttp
  • API返回的數據爲JSON格式,在此我使用的是Gson對返回數據解析.請使用最新版的Gson
  • butterknife是用來View綁定的,可以不用寫那些煩人的findViewById

返回的數據格式

使用的是百度的API Store提供的API,地址在此:手機號碼歸屬地__API服務_API服務_API Store.

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Q0CXFzTS-1583330214728)(http://7xjhi6.com1.z0.glb.clouddn.com/Retrofit_Demo_Phone_API.png)]

該接口的API主機地址爲:http://apis.baidu.com,資源地址爲:/apistore/mobilenumber/mobilenumber
需要一個key等於apikey的Header和一個key等於phone的查詢關鍵字,而且該請求爲GET請求.

所以我們需要構造一個GET請求,添加一個Header,添加一個Query關鍵字,訪問該API返回的數據格式如下:

{
    "errNum": 0,
    "retMsg": "success",
    "retData": {
        "phone": "15210011578",
        "prefix": "1521001",
        "supplier": "移動",
        "province": "北京",
        "city": "北京",
        "suit": "152卡"
    }
}

根據返回結果我們創建數據對象PhoneResult,如下:

public class PhoneResult {
    /**
     * errNum : 0
     * retMsg : success
     * retData : {"phone":"15210011578","prefix":"1521001","supplier":"移動","province":"北京","city":"北京","suit":"152卡"}
     */
    private int errNum;
    private String retMsg;
    /**
     * phone : 15210011578
     * prefix : 1521001
     * supplier : 移動
     * province : 北京
     * city : 北京
     * suit : 152卡
     */
    private RetDataEntity retData;

    public void setErrNum(int errNum) {
        this.errNum = errNum;
    }

    public void setRetMsg(String retMsg) {
        this.retMsg = retMsg;
    }

    public void setRetData(RetDataEntity retData) {
        this.retData = retData;
    }

    public int getErrNum() {
        return errNum;
    }

    public String getRetMsg() {
        return retMsg;
    }

    public RetDataEntity getRetData() {
        return retData;
    }

    public static class RetDataEntity {
        private String phone;
        private String prefix;
        private String supplier;
        private String province;
        private String city;
        private String suit;

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public void setSupplier(String supplier) {
            this.supplier = supplier;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public void setSuit(String suit) {
            this.suit = suit;
        }

        public String getPhone() {
            return phone;
        }

        public String getPrefix() {
            return prefix;
        }

        public String getSupplier() {
            return supplier;
        }

        public String getProvince() {
            return province;
        }

        public String getCity() {
            return city;
        }

        public String getSuit() {
            return suit;
        }
    }
}

注:AndroidStudio有個插件 GsonFormat可以很方便地將Json數據轉爲Java對象.

實現過程

構建

首先,按照官方的說明,我們需要創建一個接口,返回Call<PhoneResult>

官方範例:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

這裏我們創建一個名爲PhoneService的接口,返回值爲Call<PhoneResult>,如下:

public interface PhoneService {
    @GET("")
    Call<PhoneResult> getResult();
}

首先我們需要填寫API的相對地址:/apistore/mobilenumber/mobilenumber

public interface PhoneService {
    @GET("/apistore/mobilenumber/mobilenumber")
    Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);
}

接着我們要添加一個Header和一個Query關鍵字,在這裏我們需要使用Retrofit提供的註解:

  • @Header用來添加Header
  • @Query用來添加查詢關鍵字

那麼,我們的接口就如下了:

public interface PhoneService {
    @GET("/apistore/mobilenumber/mobilenumber")
    Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);
}

使用

構建好接口以後,可以使用了!

使用分爲四步:

  1. 創建Retrofit對象
  2. 創建訪問API的請求
  3. 發送請求
  4. 處理結果

代碼如下所示:

private static final String BASE_URL = "http://apis.baidu.com";
private static final String API_KEY = "8e13586b86e4b7f3758ba3bd6c9c9135";

private void query(){
	//1.創建Retrofit對象
    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())//解析方法
            .baseUrl(BASE_URL)//主機地址
            .build();
            
    //2.創建訪問API的請求
    PhoneService service = retrofit.create(PhoneService.class);
    Call<PhoneResult> call = service.getResult(API_KEY, phoneView.getText().toString());
    
    //3.發送請求
    call.enqueue(new Callback<PhoneResult>() {
        @Override
        public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {
	        //4.處理結果
            if (response.isSuccess()){
                PhoneResult result = response.body();
                if (result != null){
                    PhoneResult.RetDataEntity entity = result.getRetData();
                }
            }
        }

        @Override
        public void onFailure(Call<PhoneResult> call, Throwable t) {

        }
    });
}

可能會有疑問:第一步中的解析方法GsonConverterFactory.create()是個啥?

官方文檔也說明了,這是用來轉換服務器數據到對象使用的.該Demo中使用API返回的數據是JSON格式,故此使用Gson來轉換,如果服務器返回的是其他類型的數據,則根據需要編寫對應的解析方法.

驗證

好了,現在可以驗證一下了!

編譯APP,安裝到手機,界面如下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-L7eP8Xmx-1583330214729)(http://7xjhi6.com1.z0.glb.clouddn.com/Retrofit_Demo_Phone_APP_001.png)]

輸入手機號碼,然後點擊查詢按鈕,結果如下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-RN41XTXI-1583330214729)(http://7xjhi6.com1.z0.glb.clouddn.com/Retrofit_Demo_Phone_APP_002.png)]

項目代碼詳見此處:Dev-Wiki/RetrofitDemo

更多文章請訪問我的博客:DevWiki Blog

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章