歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android實現號碼歸屬地查詢

Android實現號碼歸屬地查詢

日期:2017/3/1 11:16:59   编辑:Linux編程

我們通過發送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中提供了電話歸屬地查詢的使用說明

效果圖:

示例代碼:

  1. public class XmlService {
  2. public String query(String num) throws Exception {
  3. InputStream in = this.getClass().getClassLoader().getResourceAsStream("query.xml");
  4. byte[] data = LoadUtils.load(in);
  5. String xml = new String(data);
  6. //替換
  7. xmlxml = xml.replace("#", num);
  8. byte[] sendData = xml.getBytes("UTF-8");
  9. //發送到代理的地址上
  10. URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
  11. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  12. conn.setRequestMethod("POST");
  13. conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
  14. conn.setRequestProperty("Content-Length", String.valueOf(sendData.length));
  15. //將請求的xml發送出去
  16. conn.setDoOutput(true);
  17. conn.getOutputStream().write(sendData);
  18. //獲取從服務器傳回來的數據
  19. if (conn.getResponseCode() == 200)
  20. return parse(conn.getInputStream());
  21. return null;
  22. }
  23. //解析流拿到getMobileCodeInfoResult中的數據
  24. private String parse(InputStream inputStream) throws Exception {
  25. XmlPullParser parser = Xml.newPullParser();
  26. parser.setInput(inputStream, "UTF-8");
  27. //查找getMobileCodeInfoResult標簽,獲取標簽中的數據
  28. for (int event = parser.getEventType(); event != XmlPullParser.END_DOCUMENT; event = parser.next())
  29. switch (event) {
  30. case XmlPullParser.START_TAG:
  31. if ("getMobileCodeInfoResult".equals(parser.getName()))
  32. return parser.nextText();
  33. }
  34. return null;
  35. }
  36. }
Copyright © Linux教程網 All Rights Reserved