android访问webservice

功能:通过android访问webservice实现手机号码归属地查询。

1.编写业务逻辑

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import cn.kafei.utils.StreamTool;
/**
 * 调用webservice业务类
 */
public class AddressService {
	/**
	 * 获取手机号归属地
	 * 
	 * @param mobile手机号
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	public static String getAddress(String mobile) throws Exception,
			IOException {
		// 读取SOAP协议
		String soap = readSoap();
		soap = soap.replaceAll("\\$mobile", mobile);// 将$mobile替换为手机号码
		// 获取加载的XML数据字节数组,目的是将XML发送至服务器
		byte[] entity = soap.getBytes();
		String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";// webservice地址
		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) {
			// 发送XML,并且返回结果为XML形式,解析XML文件获得查询结果
			return parseSOAP(conn.getInputStream());
		}
		return String.valueOf(conn.getResponseCode());
	}

	/**
	 * 解析返回的XML数据
	 * 
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	private static String parseSOAP(InputStream xml) throws Exception {
		// <?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>
		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;
	}

	/**
	 * 读取SOAP协议
	 * 
	 * @return
	 * @throws Exception
	 */
	private static String readSoap() throws Exception {
		InputStream inputStream = AddressService.class.getClassLoader()
				.getResourceAsStream("soap12.xml");
		byte[] data = StreamTool.read(inputStream);
		return new String(data);
	}
}

SOAP协议XML文件,放在src目录(soap12.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>$mobile</mobileCode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>


读取流中的数据方法

/**
	 * 读取流中的数据
	 */
	public static byte[] read(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		byte[] b=new byte[1024];
		int len=0;
		while((len=inputStream.read(b))!=-1){
			outputStream.write(b,0,len);
		}
		inputStream.close();
		return outputStream.toByteArray();
	}
2.在activity中调用:

/**
	 * 查询手机号归属地
	 * 
	 * @param v
	 */
	public void query(View v) {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);// 控制键盘显示和隐藏
			String mobile = mobileText.getText().toString().trim();// 获取手机号码
			try {
				String address = AddressService.getAddress(mobile);// 查询归属地
				textView.setText(address.equals("403")? this.getString(R.string.connError) : address);// 显示查询结果
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 强制隐藏键盘
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.error, 1)
						.show();
			}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值