发送xml数据和调用webservice

本文介绍了一种通过调用WebService API查询手机号码归属地的方法。使用SOAP协议构造XML请求,并通过HTTP POST方式发送,最后解析返回的XML数据获取归属地信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

调用xml数据(包含方法参数)来获取webservice中的api返回值,XML遵循soap协议

获取XML输入流,调用webserce的AP,解析返回的API,从而获得归属地查询结果,其中String为占位符,可替换

public class AddressService {
/**
* 获取手机号归属地
* @param mobile 手机号
* @return
* @throws Exception
*/
public static String getAddress(String mobile) throws Exception{
String soap = readSoap();
soap = soap.replaceAll("\\$mobile", mobile);
byte[] entity = soap.getBytes();

String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
conn.getOutputStream().write(entity);
if(conn.getResponseCode() == 200){
return parseSOAP(conn.getInputStream());
}
return null;
}

发送的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>
	    <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">
	      <getMobileCodeInfoResult>string</getMobileCodeInfoResult>
	    </getMobileCodeInfoResponse>
	  </soap12:Body>
	</soap12:Envelope>
	 */

解析返回的xml数据的归属地结果

private static String parseSOAP(InputStream xml)throws Exception{
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml, "UTF-8");
		int event = pullParser.getEventType();
		while(event != XmlPullParser.END_DOCUMENT){
			switch (event) {
			case XmlPullParser.START_TAG:
				if("getMobileCodeInfoResult".equals(pullParser.getName())){
					return pullParser.nextText();
				}
				break;
			}
			event = pullParser.next();
		}
		return null;
	}
//获得xml输入流
	private static String readSoap() throws Exception{
		InputStream inStream = AddressService.class.getClassLoader().getResourceAsStream("soap12.xml");
		byte[] data = StreamTool.read(inStream);
		return new String(data);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值