Android 请求WebService 并且解析

直接上代码:

写一个Bean,封装数据

package com.mbl.wbsconn;

import java.util.List;
import java.util.Map;

public class BaseBean {
	
	protected String usid;
	
	protected String pwd;
	
	protected String error;
	
	protected String msgtp;
	
	protected String logonstatus;
	
	
	protected  List<Map> nodes=null;
	
	

	public String getMsgtp() {
		return msgtp;
	}

	public void setMsgtp(String msgtp) {
		this.msgtp = msgtp;
	}

	public String getUsid() {
		return usid;
	}

	public void setUsid(String usid) {
		this.usid = usid;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	public String getLogonstatus() {
		return logonstatus;
	}

	public void setLogonstatus(String logonstatus) {
		this.logonstatus = logonstatus;
	}

	public List<Map> getNodes() {
		return nodes;
	}

	public void setNodes(List<Map> nodes) {
		this.nodes = nodes;
	}
	
	
	
}

package com.mbl.wbsconn;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

public class MyWebService {
	private static final String Tag = "MyWebService";
	protected static final String NAMESPACE = "http://127.0.0.1";
	protected static final String SOAP_ACTION = "http://127.0.0.1";// 与服务端的nameSpace要一致(默认为反向包名)
	private String nameSpace = NAMESPACE;// 与服务端的nameSpace要一致(默认为反向包名)
	private String soap_action = SOAP_ACTION;
	private HttpTransportSE httpTransportSE;

	public MyWebService(String nameSpace, String soap_action, String wsdlUrl) {
		super();
		this.nameSpace = nameSpace;
		this.soap_action = soap_action;
		httpTransportSE = new HttpTransportSE(wsdlUrl, 10000);
	}

	public String getNameSpace() {
		return nameSpace;
	}

	public String getSoap_action() {
		return soap_action;
	}

	public HttpTransportSE getHttpTransportSE() {
		return httpTransportSE;
	}

	public Object invoke(String methodNmae, WebserviceProperty... properties)
			throws IOException, XmlPullParserException {
		return invoke(methodNmae, SoapEnvelope.VER11, false, false, properties);
	}

	public Object invoke(String methodNmae, int version, boolean dotNet,
			boolean debug, WebserviceProperty... properties)
			throws IOException, XmlPullParserException {
		SoapObject soapObject = new SoapObject(nameSpace, methodNmae);
		if (properties != null) {
			for (WebserviceProperty webserviceProperty : properties) {
				soapObject.addProperty(webserviceProperty.getName(),
						webserviceProperty.getValue());
			}

			Log.i(Tag, "soapObject --- " + soapObject.toString());
		}
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				version);
		envelope.bodyOut = soapObject;
		envelope.dotNet = dotNet;
		envelope.setOutputSoapObject(soapObject);
		httpTransportSE.debug = debug;
		httpTransportSE.call(soap_action, envelope);
		// soapObject = (SoapObject) envelope.bodyIn;
		Object obj = envelope.getResponse();

		return obj;
	}

<pre name="code" class="html">
package com.mbl.wbsconn;

import org.ksoap2.SoapEnvelope;

import android.util.Log;

/**
 * webservice 处理类
 * 
 * @author Administrator
 */
public class WebserviceHandle {

	private static final String Tag = "WebserviceHandle";

	public static String urlWebString = Sysconfig._urlWebString;
	public static String url = Sysconfig._url;
	public static String nameSpace = Sysconfig._nameSpace;
	public static String soap_action = Sysconfig._soap_action;

	public static String webXml = "";

	public WebserviceHandle() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 * @param method
	 * @param param
	 * @return
	 * @throws Exception
	 * @date 2013-10-22 下午5:00:57
	 */
	public static String getWebserviceXml(String method, Object[][] param)
			throws Exception {
		MyWebService service = new MyWebService(nameSpace, soap_action, url);
		/*
		 * WebserviceProperty property = new WebserviceProperty();
		 * property.setName("usid"); property.setValue("lxsyg01");
		 */
		/*
		 * WebserviceProperty property1 = new WebserviceProperty(); String pass
		 * = "11111111"; pass = Tools.md5Encode(pass); property1.setName("pwd");
		 * property1.setValue(pass);
		 */

		WebserviceProperty[] pro = new WebserviceProperty[param.length];
		for (int i = 0; i < param.length; i++) {
			WebserviceProperty property = new WebserviceProperty();
			property.setName(param[i][0].toString());
			property.setValue(param[i][1]);

			pro[i] = property;
		}

		Object obj = null;

		obj = service.invoke(method, SoapEnvelope.VER11, true, true, pro);

		// System.out.println("webserviceHandler --- "+obj.toString());

		return obj.toString();
	}

	public static String getWebserviceXml(String method, String methodCode,
			String[] param, String md5str) throws Exception {
		Log.i(Tag, "url --- " + url);
		Log.i(Tag, "nameSpace --- " + nameSpace);
		Log.i(Tag, "soap_action --- " + soap_action);

		MyWebService service = new MyWebService(nameSpace, soap_action, url);
		/*
		 * WebserviceProperty property = new WebserviceProperty();
		 * property.setName("usid"); property.setValue("lxsyg01");
		 */
		/*
		 * WebserviceProperty property1 = new WebserviceProperty(); String pass
		 * = "11111111"; pass = Tools.md5Encode(pass); property1.setName("pwd");
		 * property1.setValue(pass);
		 */

		WebserviceProperty[] pro = new WebserviceProperty[3];
		WebserviceProperty property = new WebserviceProperty("method",
				methodCode);
		pro[0] = property;

		StringBuffer paramter = new StringBuffer();
		for (int i = 0; i < param.length; i++) {
			paramter.append(param[i]);
			if (i < param.length - 1) {
				paramter.append("|");
			}
		}
		WebserviceProperty property1 = new WebserviceProperty("params",
				paramter.toString());
		// admin|12345
		pro[1] = property1;

		WebserviceProperty property2 = new WebserviceProperty("md5str", "");
		pro[2] = property2;

		Object obj = null;

		obj = service.invoke(method, SoapEnvelope.VER11, true, true, pro);

		// System.out.println("webserviceHandler --- "+obj.toString());

		return obj.toString();
	}

}

}


package com.mbl.wbsconn;

public class WebserviceProperty {
	private String name;//参数名
	private Object value;//参数值
	
	public WebserviceProperty() {
//		System.out.println("WebserviceProperty A  ========================");
//		super();
	}
	public WebserviceProperty(String name, Object value) {
//		System.out.println("WebserviceProperty B  ========================");
//		super();
		this.name = name;
		this.value = value;
	}
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Object getValue() {
		return value;
	}
	public void setValue(Object value) {
		this.value = value;
	}
	
}


解析XML
package com.mbl.wbsconn;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;



public class ObjectParse  {
	

	public static BaseBean XmlToObject(String xml) throws Exception {
		SAXParserFactory factory = SAXParserFactory.newInstance(); // 取得SAXParserFactory实例
		SAXParser parser = factory.newSAXParser(); // 从factory获取SAXParser实例
		MyHandler handler = new MyHandler(); // 实例化自定义Handler
		InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
		parser.parse(is, handler); // 根据自定义Handler规则解析输入流
		return handler.getBaseModel();
	}

	
	public static String ObjectToXml(BaseBean baseModel) throws Exception {
		SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();// 获取SaxTransformerFactory实例
		TransformerHandler handler = factory.newTransformerHandler();// 从factory获取handler实例
		Transformer transformer = handler.getTransformer();// 从handler中获取transformer实例
		transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); // 设置输出采用的编码方式
		transformer.setOutputProperty(OutputKeys.INDENT, "no");// 是否自动添加额外空白
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");// 是否忽略xml声明
//		transformer.setOutputProperty(OutputKeys., value)
		StringWriter writer = new StringWriter();
		Result result = new StreamResult(writer);
		handler.setResult(result);
		char[] ch = null;
		String uri = "";// 代表命名空间的URI 当URI无值时需要赋值空字符串
		String localName = "";// 命名空间本地名称(不包含前缀)未处理时须织空字符串
		handler.startDocument();// 开始文本
		handler.startElement(uri, localName, "ticketbook", null);// 开始创建节点
		ch = baseModel.getUsid().toCharArray();
		handler.startElement(uri, localName, "usid", null);// 开始借点 用户名
		handler.characters(ch, 0, ch.length);// 设置节点文本值
		handler.endElement(uri, localName, "usid");// 结束节点
		handler.startElement(uri, localName, "pwd", null);// 开始借点 用户名
		ch = baseModel.getPwd().toCharArray();
		if(ch==null||ch.length==0){
			handler.characters("****".toCharArray(), 0,"****".length());// 设置节点文本值
		}else{
			handler.characters(ch, 0, ch.length);// 设置节点文本值
		}
		handler.endElement(uri, localName, "pwd");// 结束节点
		handler.startElement(uri, localName, "logonstatus", null);
		ch = baseModel.getLogonstatus().toCharArray();
		handler.characters(ch, 0, ch.length);// 设置logon状态
		handler.endElement(uri, localName, "logonstatus");
		// 如果有状态正常且有数据则继续添加节点
		if (baseModel.getLogonstatus() != null && !"".equals(baseModel.getLogonstatus()) && "true".equals(baseModel.getLogonstatus())) {
			if (baseModel.getNodes() != null && baseModel.getNodes().size() > 0) {
				List nodes = baseModel.getNodes();
				for (int y = 0; y < nodes.size(); y++) {// 循环节点
					handler.startElement(uri, localName, "nodes", null);
					Map map = (Map) nodes.get(y);
					Iterator sitertor = map.keySet().iterator();
					while (sitertor.hasNext()) {
						String skey = sitertor.next().toString();
						if (map.get(skey) != null) {
							ch = map.get(skey).toString().toCharArray();
						}else {
							ch = "NULL".toCharArray(); 
						}
						handler.startElement(uri, localName, skey, null);
						handler.characters(ch, 0, ch.length);// 设置logon状态
						handler.endElement(uri, localName, skey);
					}
					handler.endElement(uri, localName, "nodes");
				}
			}
		}
		handler.endElement(uri, localName, "ticketbook");
		handler.endDocument();
		return writer.toString();
	}

	private static class MyHandler extends DefaultHandler {

		private BaseBean baseModel = null;
		private StringBuilder builder;
		private Map map;

		public BaseBean getBaseModel() {
			return baseModel;
		}

		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			baseModel = new BaseBean();
			builder = new StringBuilder();
		}

		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			builder.setLength(0);
			/*if (qName.equals("usid")) {
				baseModel.setUsid(builder.toString());
			} else if (qName.equals("logonstatus")) {
				baseModel.setLogonstatus(builder.toString());
			} else if (qName.equals("pwd")) {
				baseModel.setPwd(builder.toString());
			} else */
			if (qName.equals("menu")) {
				if (baseModel.getNodes() == null) {
					baseModel.setNodes(new ArrayList<Map>());
				}
				map = new HashMap();
			}
			if (qName.equals("nodes")) {
				if (baseModel.getNodes() == null) {
					baseModel.setNodes(new ArrayList<Map>());
				}
				map = new HashMap();
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
			if(qName.equals("error")){
				baseModel.setError(builder.toString());
			}else if (qName.equals("usid")) {
				baseModel.setUsid(builder.toString());
			} else if (qName.equals("logonstatus")) {
				baseModel.setLogonstatus(builder.toString());
			} else if (qName.equals("pwd")) {
				baseModel.setPwd(builder.toString());
			} else if (qName.equals("menu")) {
				baseModel.getNodes().add(map);
			} else if (qName.equals("nodes")) {
				baseModel.getNodes().add(map);
			} else {
				if(map!=null){
					map.put(qName, builder.toString());
				}
			}
		}

		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
			super.characters(ch, start, length);
			builder.append(ch, start, length); // 将读取的字符数组追加到builder中
		}
	}




}
public class UrlAddr {

	private static final String Tag = "UrlAddr";

	public static String getInfo(String method_code, String username,
			String userpass) {
		String resultString = "";
		try {
			resultString = WebserviceHandle.

			getWebserviceXml(Sysconfig.METHOD, method_code, new String[] {
					Sysconfig.SYS_USERNAME, Sysconfig.SYS_USERPASS, username,
					userpass}, Sysconfig.SYSMD5_STR);
			Log.d(Tag, resultString);
		} catch (Exception e) {
			Log.d(Tag, resultString, e);
			e.printStackTrace();
		}

		return resultString;

	}
}


配置连接

package com.mbl.wbsconn;

public class Sysconfig {
	// MyWebService

	public static final String METHOD = "getMessInfo";
	public static final String SYS_USERNAME = "admin";

	public static final String SYS_USERPASS = "12345678";
	public static final String SYSMD5_STR = "";

	

	public static String _urlWebString = "/services/androidBook?wsdl";
	public static String _url = "http://192.168.1.146:8090/services/androidBook?wsdl";
	public static String _nameSpace = "http://192.168.1.146:8090/";
	public static String _soap_action = "http://192.168.1.146:8090/";

}


测试:

// 请求网络拿数据

	private class TestThread extends Thread {

		@Override
		public void run() {
			Looper.prepare();
			resultString = UrlAddr.getInfo("43", "", "");//
			ArrayList<SearchBean> bean = Parse.ParseSearchAddress(resultString);
			if (resultString != null) {
				Log.i(TAG, "" + resultString + "======" + bean.size());

				Message msg = new Message();
				msg.obj = resultString;
				handler.sendMessage(msg);
			} else {
				Log.i(TAG, "没有数据");
			}

			Looper.loop();
		}
	}





Android 请求WebService 并且解析,布布扣,bubuko.com

Android 请求WebService 并且解析

上一篇:java语言安全机制浅析


下一篇:uni-app引入css动画库