Android Request WebService and parse

Source: Internet
Author: User
Tags dotnet wsdl

Directly on the code:

Write a bean that encapsulates the data

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";p rotected static final String NAMESPACE = "http://127 .0.0.1 ";p rotected static final String soap_action =" http://127.0.0.1 ";//Same as namespace on server (default is reverse package name) private string NameSpace = namespace;//is consistent with server NameSpace (default is reverse package name) 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 processing class * * @author administ Rator */public class Webservicehandle {private static final string Tag = "Webservicehandle";p ublic static string urlwebstr ing = sysconfig._urlwebstring;public static string url = sysconfig._url;public static string nameSpace = Sysconfig._namesp Ace;public static string soap_action = Sysconfig._soap_action;public static string webxml = "";p ublic Webservicehandle () { TODO auto-generated Constructor stub}/** * * @param method * @param param * @return * @throws Exception * @date 2013-1 0-22 pm 5:00:57 */public static string Getwebservicexml (String method, object[][] param) throws Exception {MyWebService ser vice = 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++) {Webservicepro Perty property = new Webserviceproperty ();p roperty.setname (param[i][0].tostring ());p Roperty.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 {Lo G.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 Webserviceprop Erty (); * 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);p ro[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|12345pro[1] = property1; Webserviceproperty property2 = new Webserviceproperty ("Md5str", "");p ro[2] = Property2;object obj = Null;obj = Service.inv Oke (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;//parameter name private Object value;//parameter 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;}}


Parsing 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 (); Get SAXParserFactory instance SAXParser parser = Factory.newsaxparser (); Get SAXParser instance from factory MyHandler handler = new MyHandler (); Instantiate custom Handlerinputstream is = new Bytearrayinputstream (xml.getbytes ("Utf-8"));p Arser.parse (is, handler); Parse the input stream according to custom handler rules return Handler.getbasemodel ();} public static String Objecttoxml (Basebean basemodel) throws Exception {Saxtransformerfactory factory = ( saxtransformerfactory) transformerfactory.newinstance ();//Get saxtransformerfactory instance Transformerhandler handler = Factory.newtransformerhandler ();//Get handler instance from factory transformer transformer = Handler.gettransformer ();// Get transformer Instance Transformer.setoutputproperty (outputkeys.encoding, "Utf-8") from handler; Set the output to use the encoding method Transformer.setoutputproperty (Outputkeys.indent, "no"),//whether to automatically add additional blank Transformer.setoutputproperty ( Outputkeys.omit_xml_declaration, "yes");//Ignore XML declaration//transformer.setoutputproperty (Outputkeys., value) StringWriter writer = new StringWriter (); Result result = new Streamresult (writer); Handler.setresult (result); char[] ch = null; String uri = "";//URI that represents the namespace when the URI has no value, you need to assign a value to the empty string localname = "";//namespace local name (without prefix) is not locatedHandler.startdocument ();//Start Text handler.startelement (URI, LocalName, "Ticketbook", null);//start creating node ch = Basemodel.getusid (). ToCharArray () handler.startelement (URI, LocalName, "Usid", null);//Start borrowing the user name Handler.characters ( CH, 0, ch.length);//Set the node text value handler.endelement (URI, LocalName, "Usid");//End Node Handler.startelement (URI, LocalName, " PWD ", null);//Start borrowing the user name ch = basemodel.getpwd (). ToCharArray (); if (ch==null| | ch.length==0) {handler.characters ("* * * *". ToCharArray (), 0, "* * *". Length ());//Set the node text value}else{handler.characters (CH, 0, ch.length);//Set the node text value}handler.endelement (URI, LocalName, "pwd");//End Node Handler.startelement (URI, LocalName, " Logonstatus ", null); ch = basemodel.getlogonstatus (). ToCharArray (); handler.characters (CH, 0, ch.length);// Set the logon status Handler.endelement (URI, LocalName, "logonstatus");//If there is a normal state and there is data continue to add node 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++) {//Loop node Handler.startelement (URI, LocalName, "nodes", null); Map map = (map) nodes.get (y), Iterator sitertor = Map.keyset (). Iterator (); while (Sitertor.hasnext ()) {String Skey = Siterto R.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);//Set logon status 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;pri Vate Map map;public Basebean Getbasemodel () {return basemodel;} @Overridepublic void Startdocument () throws Saxexception {super.startdocument (); Basemodel = new Basebean (); builder = new StringBuilder ();} @Overridepublic 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 ())}, or 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 ();}} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {super.endelement (URI, lo Calname, 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 ())}, or 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 ());}}} @Overridepublic void characters (char[] ch, int start, int length) throws saxexception {super.characters (ch, start, length) ; builder.append (ch, start, length); Append the read character array to the Builder}}}
public class Urladdr {private static final string Tag = "Urladdr";p ublic 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;}}


Configure the connection

Package Com.mbl.wbsconn;public class Sysconfig {//mywebservicepublic static final String METHOD = "Getmessinfo";p Ublic St Atic final String sys_username = "Admin";p ublic static final String sys_userpass = "12345678";p ublic static final string S Ysmd5_str = "";p ublic static string _urlwebstring = "/services/androidbook?wsdl";p ublic static string _url = "http://192.1 68.1.146:8090/SERVICES/ANDROIDBOOK?WSDL ";p ublic static String _namespace =" http://192.168.1.146:8090/";p ublic static String _soap_action = "http://192.168.1.146:8090/";}


Test:

Request network take data private class Testthread extends Thread {@Overridepublic void run () {looper.prepare (); resultstring = urladdr.ge Tinfo ("n", "", "");//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, "no Data");} Looper.loop ();}}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.