編輯:關於Android編程
本文實例講述了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>
希望本文所述對大家Android程序設計有所幫助。
Android中使用Socket
Socket簡介在說Socket之前,我們有必要先來簡單介紹一下TCP/IP協議族,TCP/IP(Transmission Control Protocol/Intern
編寫簡易Android天氣應用的代碼示例
本文所要介紹的簡易天氣App主要用RxAndroid、MVP、Retrofit實現,首先來看看效果:主頁內容:右側欄天氣列表:左側欄城市列表首先看看Activity主要代
Android上下文服務管理查詢過程
在開發Android應用程序時,如果需要使用系統提供的服務,可以通過服務名稱調用山下文的getSystemService(String name)來獲取服務管理者,那麼該
Dialog在android中的應用(一)
如果做一個如下圖的Dialog,首先要定義樣式: stateUnchanged|adjustResize @null @null