Android Universal use WebServices (without introducing external packages)

Source: Internet
Author: User

Directly on the code

Webserviceslib.java

 Packagecom.example.testwebservices;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportJava.util.Map;ImportOrg.xmlpull.v1.XmlPullParser;Importandroid.util.Xml;//import Javax.xml.parsers.DocumentBuilder;//import javax.xml.parsers.DocumentBuilderFactory;////import org.w3c.dom.Document;//import org.w3c.dom.Element;//import org.w3c.dom.NodeList; Public classWebserviceslib {/*** Call WebServices * *@paramserver_url webservices Address *@paramservicenamespace webservices Namespace *@paramfunctionname Function Name *@paramparams parameter list (name must correspond) *@returnreturn results *@throwsException*/     Public StaticString Invokews (String Server_url, String servicenamespace, string functionname, map<string, string> params)throwsException {stringbuffer Strbuff=NewStringBuffer (); Strbuff.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "? >\n"); Strbuff.append ("<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\ ">\n"); Strbuff.append ("<soap12:body>\n"); if(params==NULL|| Params.size () ==0) {strbuff.append ("<" + functionname + "xmlns=\" "+ servicenamespace +" \ "/>\n"); } Else{strbuff.append ("<" + functionname + "xmlns=\" "+ servicenamespace +" \ ">\n");  for(Map.entry<string, string>Entry:params.entrySet ()) {Strbuff.append ("<" +entry.getkey () + ">" + entry.getvalue () + "</" +entry.getkey () + ">\n"); } strbuff.append ("</" + functionname + ">\n"); } strbuff.append ("</soap12:body>\n"); Strbuff.append ("</soap12:Envelope>");//return strbuff.tostring ();                byte[] data =strbuff.tostring (). GetBytes (); //submit a POST requestURL url =NewURL (Server_url); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("POST"); Conn.setconnecttimeout (5 * 1000); Conn.setdooutput (true); Conn.setrequestproperty ("Content-type", "application/soap+xml; Charset=utf-8 "); Conn.setrequestproperty ("Content-length", String.valueof (data.length)); OutputStream OutStream=Conn.getoutputstream ();        Outstream.write (data);        Outstream.flush ();        Outstream.close (); intResponsecode =Conn.getresponsecode (); if(Responsecode = = 200) {InputStream instream=Conn.getinputstream (); Xmlpullparser Parser=Xml.newpullparser (); Parser.setinput (instream,"UTF-8"); intEventType = Parser.geteventtype ();//produce the first event             while(EventType! =xmlpullparser.end_document) {                //as long as it is not a document end event                Switch(eventtype) { CaseXmlPullParser.START_TAG:String name= Parser.getname ();//gets the name of the element that the parser is currently pointing to                    if((functionname+ "Result"). Equals (name)) {returnParser.nexttext (); }                     Break; } EventType=Parser.next (); }            return""; }        return"Error:" +Responsecode; }}

Calling methods

Mainactivity.java

 Packagecom.example.testwebservices;ImportJava.util.HashMap;ImportJava.util.Map;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateTextView mobileaddress; Private Static Final intmsg_success = 0;//     Private Static Final intMsg_failure = 1;//     PrivateThread Mthread; Private BooleanIsRunning =false; /*** Asynchronous Invocation*/    PrivateHandler Mhandler =NewHandler () { Public voidHandlemessage (Message msg) {//This method runs on the UI thread            Switch(msg.what) { CaseMSG_SUCCESS:mobileAddress.setText (msg.obj.toString ()); Toast.maketext (Getapplication (),"Query succeeded", Toast.length_long). Show ();  Break;  CaseMSG_FAILURE:mobileAddress.setText (msg.obj.toString ()); Toast.maketext (Getapplication (),"Query Failed", Toast.length_long). Show ();  Break; } isrunning=false;    }    }; Runnable Runnable=NewRunnable () {@Override Public voidrun () {//reading an XML file            Try{Map<string, string> params =NewHashmap<string, string>(); String Add=Webserviceslib.invokews ("Http://192.168.1.149:6666/WebServices/SystemRoles.asmx",                        "http://tempuri.org/", "Getallsystemroles", params);            Mhandler.obtainmessage (msg_success, add). Sendtotarget (); } Catch(Exception e) {mhandler.obtainmessage (Msg_failure,e.getmessage ()). Sendtotarget ();    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Mobileaddress= (TextView) This. Findviewbyid (r.id.mobileaddress); Button btnsearch= (Button) This. Findviewbyid (R.id.btnsearch); Btnsearch.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View arg0) {//HTTP request cannot be requested in the main thread after Android 4.0                if(!isrunning) {isrunning=true; Mthread=NewThread (runnable); Mthread.start ();//Thread Start}Else{Toast.maketext (Getapplication (),"The thread has started. ", Toast.length_long). Show ();    }            }        }); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true; }}

Android Universal use WebServices (without introducing external packages)

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.