1. Create an Android project Ksoaptest
2. All the way Next
3. Add Ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar to Project
(The jar package will be included after the full project download later)
4. Edit Activity_main.xml
<relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" android:layout_width="Fill_parent"android:layout_height="Fill_parent" > <button android:id = "@+id/button1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignparentleft =< Span class= "Hljs-value" > "true" android:layout_alignparentright = "true" android:layout_below =" @+id/textview1 " android:layout_margintop =" 56DP " android:text =" Click Access Server HelloWorld "/> <TextViewandroid:id= "@+id/textview1"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:layout_alignparenttop= "True"android:layout_centerhorizontal="true"android:layout_margintop= "86DP" Android:text="TextView" /> </relativelayout>
5. Add base class Activity class: Baseksoapactivity.java, the code is as follows:
PackageCom.example.base;ImportJava.util.Iterator;ImportJava.util.Map;ImportOrg.ksoap2.SoapEnvelope;ImportOrg.ksoap2.serialization.SoapObject;ImportOrg.ksoap2.serialization.SoapSerializationEnvelope;ImportOrg.ksoap2.transport.HttpTransportSE;Importandroid.app.Activity;ImportAndroid.app.AlertDialog;ImportAndroid.content.DialogInterface;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;/** * * @author Wangpeng * August 7, 2015 11:24:49 * Integration of the activity of this class makes it easy to call a Web service for communication * */@SuppressWarnings("All") Public Abstract class baseksoapactivity extends Activity{ //Server link FinalString Web_service_url ="HTTP://%S/TESTSERVICE.ASMX?WSDL";//Namespace FinalString Namespace ="http://tempuri.org/";//server address PrivateString ipAddress;/** * Activity creation time execution * Get Web Service server address */ @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//IP addresses can be configured to obtain //NOTE: You cannot use 127.0.0.1 or localhost because the Android app is running on your phone and your phone cannot access IIS on your computer via 127.0.0.1 or localhost //Here I am using the IP address of my computer's wireless network card, my phone is also connected to this wireless network This. ipAddress ="192.168.20.133"; }/** * * @param Paras * * protected void Request(Object ... paras) {NewAsynctask<object, Object, soapobject> () {@Override protectedSoapobjectDoinbackground(Object ... args) {//1, specify the namespace of the Web service and the method name of the callString MethodName = (string) args[0]; Soapobject request =NewSoapobject (Namespace, MethodName);///2, set the arguments passed by the callMap<string, object> paras = (map<string, object>) args[1];//2, set the parameter value of the calling method, if there is no parameter, can be omitted, if(Paras! =NULL) {Iterator iter = Paras.entryset (). Iterator (); while(Iter.hasnext ()) {Map.entry Entry = (map.entry) iter.next (); Request.addproperty (String) Entry.getkey (), (String) entry.getvalue ()); } }///3, generates SOAP request information that invokes the Web service method. This information is described by the Soapserializationenvelope objectSoapserializationenvelope envelope =NewSoapserializationenvelope (SOAPENVELOPE.VER12); Envelope.bodyout = Request;//C # Write the application must add this sentenceEnvelope.dotnet =true; Httptransportse HT =NewHttptransportse (String.Format (Web_service_url, ipAddress));//Use the Call method to invoke the WebService method Try{Ht.call (NULL, envelope); }Catch(Exception e) {publishprogress ("Network Error","The network connection failed, check that the device is networked, and that the server address is configured. ");return NULL; }Try{Soapobject obj = (soapobject) Envelope.bodyin;returnObj }Catch(Exception e) {publishprogress ("Network Error","Server Side return results");return NULL; } }@Override protected void OnPostExecute(Soapobject obj) {Super. OnPostExecute (obj); Requestcallback (obj); }@Override protected void onprogressupdate(Object ... values) {Super. onprogressupdate (values);if(Values! =NULL&& Values.length = =2) {showmessage (String) values[0], (String) values[1]); }}}.execute (paras); }protected void ShowMessage(string title, String msg) {NewAlertdialog.builder ( This). Settitle (title). Setmessage (msg). Setpositivebutton ("OK",NewDialoginterface.onclicklistener () {@Override Public void OnClick(Dialoginterface Dialog,intwhich) {}}). Show (); }/** * All classes that inherit this activity must implement this method * This method is called at the end of each communication * * @param The return value of obj and server communication */ protected Abstract void Requestcallback(Soapobject obj);}
6. Edit Mainactivity, inherit the above baseksoapactivity, the code is as follows:
PackageCom.example.ksoaptest;ImportJava.util.HashMap;ImportJava.util.Map;ImportOrg.ksoap2.serialization.SoapObject;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;Importcom.example.base.BaseKsoapActivity; Public class mainactivity extends baseksoapactivity { PrivateButton btn;PrivateTextView TV;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); BTN = (Button) Findviewbyid (R.id.button1); TV = (TextView) Findviewbyid (R.ID.TEXTVIEW1); Btn.setonclicklistener (NewOnclicklistener () {@Override Public void OnClick(View arg0) {map<string, object> paras =NewHashmap<string, object> ();//paras.put ("argument name", "parameter Value");Request ("HelloWorld", paras); } }); }@Override protected void Requestcallback(Soapobject obj) {//Complex a bit of return value needs parsing, we're going to return a string here, so the parsing is relatively simple //For complex return types, personal advice is returned after the server is converted to a JSON string . //So the client can convert to the desired object as long as the Gson or jsonlib of the string are thrown to the third party. //And for a byte array such return value through the XML transport will add a lot of useless tags, increase the amount of data transferred, reduce efficiencyTv.settext (Obj.getproperty (0). ToString ()); }}
7. Add Network permissions in Androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
8. Running
9.c# and Android complete code uploaded
http://download.csdn.net/detail/u013816347/8999889
Welcome to comment
Copyright NOTICE: This article is the original blogger article, please indicate the source when reproduced.
Android and C # WebService based Ksoap Communication (Android)