引言
最近在做一个关于车新闻的项目,让弄个根据用户注册的手机号获取该用户手机号所在地区,刚刚听说感觉特别高大上,这也可以获得???于是就开始度娘。。查了好多资料渐渐的明白了原理。
原理介绍
(1)先上网差一些能够查询手机号获取归属地的API地址。(推荐地址:http://blog.csdn.net/liuyunfan/article/details/13624335)里面有很多API。例如:http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile=手机号码&amount=10000&callname=getPhoneNumInfoExtCallback
从网页里面浏览如图:
(2)利用java url.openstream获取URL(API地址)页面的全部内容。
(3)把获取的内容去掉一些没有用的东西转换成json结构。
(4)获取json结构中需要的城市的value值。
代码示例
<span style="color:#6666cc;font-weight: bold;"> </span>/**
* 测试手机号码是来自哪个城市的,利用拍拍网的API
* @param mobileNumber 手机号码
* @return
* @throws MalformedURLException
*/
public static String calcMobileCity(String mobileNumber) throws MalformedURLException{
String jsonString = null;
JSONArray array = null;
JSONObject jsonObject = null;
//获取拍拍网的API地址
String urlString = "http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile="+mobileNumber+"&amount=10000&callname=getPhoneNumInfoExtCallback";
StringBuffer sb = new StringBuffer();
BufferedReader buffer;
URL url = new URL(urlString);
try{
//获取URL地址中的页面内容
InputStream in = url.openStream();
// 解决乱码问题
buffer = new BufferedReader(new InputStreamReader(in,"gb2312"));
String line = null;
//一行一行的读取数据
while((line = buffer.readLine()) != null){
sb.append(line);
}
in.close();
buffer.close();
// System.out.println(sb.toString());
jsonString = sb.toString();
// 替换掉“getPhoneNumInfoExtCallback(,);<!--[if !IE]>|xGv00|6741027ad78d9b06f5642b25ebcb1536<![endif]-->”,让它能转换为JSONArray对象
jsonString = jsonString.replace("getPhoneNumInfoExtCallback(", "[");
jsonString = jsonString.replace(");<!--[if !IE]>|xGv00|6741027ad78d9b06f5642b25ebcb1536<![endif]-->", "]");
// 把jsonString转化为json对象
array = JSONArray.fromObject(jsonString);
// 获取JSONArray的JSONObject对象,便于读取array里的键值对
jsonObject = array.getJSONObject(0);
}catch(Exception e){
e.printStackTrace();
}
//从JSONObject对象中读取城市名称
return jsonObject.getString("cityname");
}<span style="color:#6666cc;font-weight: bold;">
</span>
用的话直接调用这个方法就可以了。
调用结果
打印到控制台如图:
结束语
不要被困难吓倒,不要因没有听过,没有做过的事情而退缩。勇往直前你会发现其实都很简单。。。