Android实现号码归属地查询

我们通过发送XML访问 WebService就可以实现号码的归属地查询,我们可以使用代理服务器提供的XML的格式进行设置,然后请求提交给服务器,服务器根据请求就会返回给一个XML,XML中就封装了我们想要获取的数据。

发送XML

1.通过URL封装路径打开一个HttpURLConnection

2.设置请求方式,Content-Type和Content-Length

   XML文件的Content-Type为:application/soap+xml; charset=utf-8

3.使用HttpURLConnection获取输出流输出数据

 

WebService

1.WebService是发布在网络上的API,可以通过发送XML调用,WebService返回结果也是XML数据

2.WebService没有语言限制,只要可以发送XML数据和接收XML数据即可

3.http://www.webxml.com.cn/网站上提供了一些WebService服务,我们可以对其进行调用

4.http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo中提供了电话归属地查询的使用说明

效果图:

 

核心代码:

 

public class XmlService {
	public String query(String num) throws Exception {
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("query.xml");
		byte[] data = LoadUtils.load(in);
		String xml = new String(data);
		//替换
		xml = xml.replace("#", num);
		byte[] sendData = xml.getBytes("UTF-8");
		//发送到代理的地址上
		URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(sendData.length));
		//将请求的xml发送出去
		conn.setDoOutput(true);
		conn.getOutputStream().write(sendData);

		//获取从服务器传回来的数据
		if (conn.getResponseCode() == 200)
			return parse(conn.getInputStream());

		return null;
	}

	//解析流拿到getMobileCodeInfoResult中的数据
	private String parse(InputStream inputStream) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(inputStream, "UTF-8");
		//查找getMobileCodeInfoResult标签,获取标签中的数据
		for (int event = parser.getEventType(); event != XmlPullParser.END_DOCUMENT; event = parser.next())
			switch (event) {
				case XmlPullParser.START_TAG:
					if ("getMobileCodeInfoResult".equals(parser.getName()))
						return parser.nextText();
			}
		return null;
	}
}
发送的xml封装了电话号码(query.xml):

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
      <mobileCode>#</mobileCode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>


  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傅荣康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值