Android Retrofit使用教程


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

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

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

集成

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

[代碼]xml代碼:

?
1
2
3
4
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.

該接口的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,如下:

[代碼]java代碼:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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>

官方范例:

[代碼]java代碼:

?
1
2
3
4
public interface GitHubService {
   @GET ( "users/{user}/repos" )
   Call<list<repo>> listRepos( @Path ( "user" ) String user);
}</list<repo>

 

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

[代碼]java代碼:

?
1
2
3
4
public interface PhoneService {
     @GET ( "" )
     Call<phoneresult> getResult();
}</phoneresult>

 

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

[代碼]java代碼:

?
1
2
3
4
public interface PhoneService {
     @GET ( "/apistore/mobilenumber/mobilenumber" )
     Call<phoneresult> getResult( @Header ( "apikey" ) String apikey, @Query ( "phone" ) String phone);
}</phoneresult>

 

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

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

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

 

[代碼]java代碼:

?
1
2
3
4
public interface PhoneService {
     @GET ( "/apistore/mobilenumber/mobilenumber" )
     Call<phoneresult> getResult( @Header ( "apikey" ) String apikey, @Query ( "phone" ) String phone);
}</phoneresult>

 

使用

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

使用分為四步:

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

代碼如下所示:

[代碼]java代碼:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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) {
  
         }
     });
}</phoneresult></phoneresult></phoneresult></phoneresult></phoneresult>

 

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

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

驗證

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

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

APP界面

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

結果界面

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM