本文采用retrofit網絡請求庫獲取聚合網數據,文中的例子是電話號碼歸屬地查詢,
其請求接口如下:
首先添加retrofit依賴:
compile 'com.squareup.retrofit2:retrofit:2.0.2'
如果需要解析返回的json數據,則還需要添加下面的依賴,本文解析了json:
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'定義請求接口:
public interface Phone { @GET("mobile/get") Call<PhoneNumInfo> getHaoMa(@Query("phone") String phone,@Query("key") String key); }其中PhoneNumInfo爲json解析後的數據格式,根據返回數據進行定義,可以在android studio安裝gsonformat插件,可以自動生成,生成後的數據如下:
public class PhoneNumInfo { /** * resultcode : 200 * reason : Return Successd! * result : {"province":"浙江","city":"杭州","areacode":"0571","zip":"310000","company":"中國移動","card":"移動動感地帶卡"} */ private String resultcode; private String reason; /** * province : 浙江 * city : 杭州 * areacode : 0571 * zip : 310000 * company : 中國移動 * card : 移動動感地帶卡 */ private ResultBean result; public String getResultcode() { return resultcode; } public void setResultcode(String resultcode) { this.resultcode = resultcode; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public static class ResultBean { private String province; private String city; private String areacode; private String zip; private String company; private String card; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAreacode() { return areacode; } public void setAreacode(String areacode) { this.areacode = areacode; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getCard() { return card; } public void setCard(String card) { this.card = card; } } }
初始化請求:
Retrofit retrofit=new Retrofit.Builder() .baseUrl("http://apis.juhe.cn/") .addConverterFactory(GsonConverterFactory.create())//如果不需要解析json,則不需要這行。 .build(); Phone phone=retrofit.create(Phone.class); final Call<PhoneNumInfo> call=phone.getHaoMa(meditview.getText().toString(), key);
一、採用同步請求:
如果採用同步請求,那麼不能在主線程運行下面的請求語句:
Response<PhoneNumInfo> bodyResponse = call.execute();
final String body = bodyResponse.body().getResult().getCity();//獲取返回體的字符串,這裏獲取號碼的城市二、異步請求
call.enqueue(new Callback<PhoneNumInfo>() { @Override public void onResponse(Call<PhoneNumInfo> call, Response<PhoneNumInfo> response) { mtext.setText(response.body().getResult().getCity());//顯示城市名到TextView } @Override public void onFailure(Call<PhoneNumInfo> call, Throwable t) { mtext.setText(t.getMessage());//顯示獲取網絡失敗原因 } });運行結果: