需要查询手机号的API:https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=18888888888
导入okhttp.jar和okio.jar用于网络查询。
新建一个电话的model:
package zhku.edu.searchphone.model;
/**
* Created by manRED on 2018/2/21.
*/
public class Phone {
private String telString;
private String province;
private String catName;
private String carrier;
public String getTelString() {
return telString;
}
public void setTelString(String telString) {
this.telString = telString;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
}
创建一个查询号码的类:
package zhku.edu.searchphone;
import org.json.JSONException;
import java.util.concurrent.Callable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import zhku.edu.searchphone.model.Phone;
/**
* Created by manRED on 2018/2/27.
*/
public class HandePhone implements Callable<Phone> {
private Phone phone;
private String url;
public HandePhone(String url){
this.url=url;
}
@Override
public Phone call() throws Exception {
System.out.println(url);
OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
Request request = new Request.Builder()
.url(url)//请求接口。如果需要传参拼接到接口后面。
.build();//创建Request 对象
Response response = null;
response = client.newCall(request).execute();//得到Response 对象
if (response.isSuccessful()) {
String json=response.body().string();
System.out.println(json);
phone=parseModelWithOrgJson(json);
}
return phone;
}
private Phone parseModelWithOrgJson(String json){
int index=json.indexOf("{");
json=json.substring(index,json.length());
Phone phone=new Phone();
try {
org.json.JSONObject jsonObject=new org.json.JSONObject(json);
String value=jsonObject.getString("telString");
phone.setTelString(value);
value=jsonObject.getString("province");
phone.setProvince(value);
value=jsonObject.getString("catName");
phone.setCatName(value);
value=jsonObject.getString("carrier");
phone.setCarrier(value);
} catch (JSONException e) {
e.printStackTrace();
}
return phone;
}
}
主程序中调用:使用java的线程池获取返回的数据。
HandePhone handePhone=new HandePhone(url);
ExecutorService service= Executors.newFixedThreadPool(1);
Future<Phone> future=service.submit(handePhone);
Phone phone= null;
try {
phone = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}