import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NewMobile {
public static void main(String[] args) {
System.out.println(NewMobile.getCarrier("18729293693"));
System.out.println(NewMobile.getCity("18729293693"));
}
//得到归属地
public static String getCity(String tel) {
//获取返回结果
String json = httpRequest(tel).toString();
//拆分xml页面代码
String[] a = json.split("city");
//得到归属地
String city = a[1].replace(">", "").replace("</", "");
return city;
}
//得到运营商
public static String getCarrier(String tel) {
//获取返回结果
String json = httpRequest(tel).toString();
//拆分xml页面代码
String[] a = json.split("city");
String[] b = a[2].split("supplier");
//得到运营商
String carrier = b[1].replace(">", "").replace("</", "");
return carrier;
}
/**
* 发起http请求获取返回结果
* @param tel 待查询手机号
* @return String 结果字符串
*/
public static String httpRequest(String tel) {
//组装查询地址(requestUrl 请求地址)
String requestUrl = "http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile="+tel;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
//将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
}
catch (Exception e) {
return "发起http请求后,获取返回结果失败!";
}
return buffer.toString();
}
}