Android實現號碼歸屬地查詢

來源:互聯網
上載者:User

我們通過發送XML訪問 WebService就可以實現號碼的歸屬地查詢,我們可以使用Proxy 伺服器提供的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中提供了電話歸屬地查詢的使用說明

 

 

範例程式碼:

view plain
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); 
        //替換 
        xmlxml = 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; 
    } 

作者“傅榮康專欄”
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.