標籤:
本文採用okhttp庫擷取彙總網提供的免費介面資料,完成一個手機號碼歸屬地查詢功能。
其請求介面格式如下:
資料返回結果:
首先添加gson和okhttp的引用,gson我是直接下載jar包的:
compile ‘com.squareup.okhttp3:okhttp:3.2.0‘compile files(‘C:/Users/Administrator/AndroidStudioProjects/ExOkhttp/libs/gson-2.3.1.jar‘)
採用get方法,擷取資料主要代碼如下:
OkHttpClient client=new OkHttpClient();
Request request = new Request.Builder()
.url("http://apis.juhe.cn/mobile/get?phone="+string+"&key="
+"2f121eb8bf260e938df638ec3cc2e5d4")
.get()
.build();
try{
Response response = client.newCall(request).execute();
System.out.println(response.body().string());這裡就可以列印返回的結果了
}catch (Exception e){
Log.i("json------", e.getMessage()+"/"+e.getCause());
}
解析json資料之前先根據返回資料格式定義一個JsonBean:
public class JsonBean { public String resultcode; public String reason; public Result result; public static class Result { public String province; public String city; public String areacode; public String zip; public String company; public String card; } @Override public String toString() { return "JsonBean{" + "reason=‘" + reason + ‘\‘‘ + ", resultcode=‘" + resultcode + ‘\‘‘ + ", result=" + result + ‘}‘; }}
傳入帶解析的gson資料:
Gson gson = new Gson();java.lang.reflect.Type type = new TypeToken<JsonBean>() {}.getType();JsonBean jsonBean = gson.fromJson(response.body().string(), type);
這樣就可以通過jsonBean拿到所以資料了,下面是測試結果:
本文原始碼地址:https://github.com/lovezhupumao/ExOkhttp
okhttp :https://github.com/square/okhttp/
gson解析通過okhttp擷取的json格式資料(轉載)