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中,添加按钮执行响应事件,并且添加网络访问权限,将结果打印到控制台;