日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android 向服务器发送XML数据及调用webservice

發布時間:2025/3/15 Android 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 向服务器发送XML数据及调用webservice 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先講一下webservice概念
可以看作是網絡上的API,不過不是是通過new XXX().api()調用;
調用方式:客戶端發送一段xml到服務器,在xml中指定要調用的方法的名稱,以及各項參數,當服務器得到內容后進行解析,解析出方法名稱和參數后執行相應的方法之后,將結果也封裝成xml響應發回給客戶端;客戶端再進行解析得到執行結果!

下面是一個例子,最常見的獲取手機號碼歸屬地的Demo

先看結果,為了方便,我把結果打印到控件臺:

1、設置布局文件,這里省略,看界面都能比較簡單的設計出布局文件。

2、登錄到http://www.webxml.com.cn

可以看到手機號碼歸屬地的服務請求的XML

POST /WebServices/MobileCodeWS.asmx HTTP/1.1 <!-- 請求的URI --> Host: webservice.webxml.com.cn <!--Host主機--> Content-Type: application/soap+xml; charset=utf-8 <!-- Content-Type --> Content-Length: length

?

<?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>string</mobileCode> <!--手機號碼,使用的時候用一個占位符進行替換--><userID>string</userID></getMobileCodeInfo></soap12:Body> </soap12:Envelope>

3、將上面每二個xml添加到一個xml文件中,并放在類路徑下,名為soap12.xml;其中的手機號碼用占位符替換掉,并編寫業務類;

public class MobileAddresService {// 獲取手機號歸屬地public static String gerAddress(String mobile) throws Exception,IOException {String path = "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx";HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();String soap = readSoap();soap = soap.replaceAll("\\$mobile", mobile);// 我的xml文件中手機號碼用的是$mogile替換的。byte[] entity = soap.getBytes("UTF-8");conn.setDoInput(true);conn.setConnectTimeout(10000);conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");conn.setRequestProperty("Content-Length", entity.length + "");conn.getOutputStream().write(entity);if (conn.getResponseCode() == 200) { return parseSOAP(conn.getInputStream());}return null;}private static String parseSOAP(InputStream inputStream) throws Exception {XmlPullParser parser = Xml.newPullParser();parser.setInput(inputStream, "UTF-8");int event = parser.getEventType();while (event != parser.END_DOCUMENT) {switch (event) {case XmlPullParser.START_TAG:if ("getMobileCodeInfoResult".equals(parser.getName())) {return parser.nextText();}break;}event = parser.next();}return null;}private static String readSoap() throws Exception {InputStream ins = AddresService.class.getClassLoader().getResourceAsStream("soap12.xml");byte[] data = StreamTool.read(ins);return new String(data, "UTF-8");} }

?4、在MainActivity中,添加按鈕執行響應事件,并且添加網絡訪問權限,將結果打印到控制臺;

總結

以上是生活随笔為你收集整理的Android 向服务器发送XML数据及调用webservice的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。