Square公司開源了許多優秀的庫,Retrofit就是其中之一。html
Retrofit
是用來簡化APP訪問服務器API,若是你的服務器使用的使RESTAPI,那麼趕忙使用Retrofit
吧。java
官方的文檔是用GitHub的API說明使用過程的,有的童鞋可能從沒用過GitHub的API(好比我),爲了簡單易懂,這裏我使用一個查詢手機歸屬地的API來講明Retrofit
的使用過程。android
目前我使用的是AndroidStudio
,那麼在model的build.gradle文件中添加如下引用:git
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'
說明:github
Retrofit
依賴於okhttp
,因此須要集成okhttp
json
API返回的數據爲JSON
格式,在此我使用的是Gson
對返回數據解析.請使用最新版的Gson
api
butterknife
是用來View
綁定的,能夠不用寫那些煩人的findViewById
了服務器
使用的是百度的API Store提供的API,地址在此:手機號碼歸屬地__API服務_API服務_API Store.ide
該接口的API主機地址爲:http://apis.baidu.com
,資源地址爲:/apistore/mobilenumber/mobilenumber
須要一個key等於apikey的Header和一個key等於phone的查詢關鍵字,並且該請求爲GET請求.gradle
因此咱們須要構造一個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); }
構建好接口之後,可使用了!
使用分爲四步:
建立Retrofit對象
建立訪問API的請求
發送請求
處理結果
代碼以下所示:
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,安裝到手機,界面以下:
輸入手機號碼,而後點擊查詢按鈕,結果以下:
項目代碼詳見此處:Dev-Wiki/RetrofitDemo
更多文章請訪問個人博客:DevWiki Blog