本文采用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());//显示获取网络失败原因 } });运行结果: