android访问webservice

来源:互联网 发布:网络贷款是真是假 编辑:程序博客网 时间:2024/04/20 21:26

功能:通过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();}}


原创粉丝点击