WebService called C # written in Android (with source code)

Source: Internet
Author: User
Tags wsdl

This article is available because the project uses Android to invoke WebService written in C #. In the process of learning, found in C # directly call WebService more convenient, directly add a reference, you can directly use the WebService as an object to use, the use of VS2010 code hints function can be cool and crooked to all the things you want to point out. In Android call, trouble a little, but also OK. The main thing is that we need to find out in code what the name of the method to call WebService is, what parameters to pass to WebService and the corresponding parameter names, and some additional information, such as the version number of soap, needs to be understood.

1. Preparatory work: Write a Test WebService

First, let's first prepare the Webservice,webservice code is very simple, one is to return the HelloWorld field, and the other is to return the string that the user sent to WebService.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.Services;namespacetestandroidcall{/// <summary>    ///Summary description of WebService1/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)]    //to allow the Web service to be called from the script using ASP. NET AJAX, uncomment the downstream. //[System.Web.Script.Services.ScriptService]     Public classWebService1:System.Web.Services.WebService {[WebMethod] Public stringHelloWorld () {return "Hello World"; } [WebMethod] Public stringEchomessage (stringmsg) {            returnmsg; }    }}

Next, we need to download a class library called WebService in Android

More commonly used are Ksoap2, can be downloaded from the https://code.google.com/p/wsdl2ksoap/downloads/list. You can also click here to download it directly.

Copy the downloaded Ksoap2-android-assembly-2.4-jar-with-dependencies.jar package to the Lib directory of the Eclipse Project and, of course, to the other directory. This jar package is also referenced in the Eclipse project.

2, complete the simple Android layout code to write

(1) Add permission to the Adroidmanifest.xml ,Add the following sentence to the <manifest> node

<!---<android:name= " Android.permission.INTERNET "/>

(2), we set up two buttons in Android, respectively, corresponding to the two methods in webservice

Private voidinitbtn () {View Btnhelloworld= This. Findviewbyid (R.id.btnhelloworld); Btnhelloworld.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Map<string, string> values =NewHashmap<string, string>(); Values.put ("MSG", "This is the message sent by Android phone");            Request (Method_hello_world);                }        }); View Btnechomessage= This. Findviewbyid (R.id.btnechomessage); Btnechomessage.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Map<string, string> values =NewHashmap<string, string>(); Values.put ("MSG", "This is the message sent by Android phone");            Request (method_echo_message,values);    }        }); }

In the request (... method, we want to implement the method name in webservice and the parameters of the call into the webservice. In this approach, Asynctask is used primarily to handle webservice calls, because calling WebService is a network operation that can be time-consuming, Over Android3.0, network operations are not allowed directly on the UI thread, and Asynctask can also update the controls on the UI directly.

/*** Perform asynchronous tasks * *@paramParams * Method name + parameter list (hash table Form)*/     Public voidRequest (Object ... params) {NewAsynctask<object, Object, string>() {@OverrideprotectedString doinbackground (Object ... params) {if(Params! =NULL&& Params.length = = 2) {                    returnCallwebservice (String) params[0], (Map<string, string>) params[1]); } Else if(Params! =NULL&& Params.length = = 1) {                    returnCallwebservice (String) params[0],NULL); } Else {                    return NULL; }            }            protected voidOnPostExecute (String result) {if(Result! =NULL) {Tvmessage.settext ("Server Reply info:" +result);        }            };    }.execute (params); }
3. Analyze the code of Android call WebService

Our focus will be on the callwebservice () approach. This method encapsulates some of the objects in the Ksoap2 class library that call WebService.

(1) Specify the namespace of the WebService and the method name to invoke, such as:

Soapobject request =new soapobject (namespace,methodname);

The first parameter of the Soapobject class represents the namespace of webservice, and the WebService namespace can be found from the WSDL document. The second parameter represents the name of the WebService method to invoke.

(2) Set the parameter value of the calling method, if there are no parameters, you can omit the code that sets the parameter value of the method as follows:

Request.addproperty ("param1", "value"); Request.addproperty ("param2", "value");

Note that the 1th parameter of the AddProperty method represents the parameter name of the calling method, which is the same as the method parameter name in the WebService class on the service side, and the order of the parameters is the same.

(3) Generates SOAP request information that calls the WebService method. This information is described by the Soapserializationenvelope object, and the code is:

Soapserializationenvelope envelope=New= Request;

When you create a Soapserializationenvelope object, you need to set the version number of the SOAP protocol through the Soapserializationenvelope class's construction method. This version number needs to be set according to the version number of the server webservice. After you create the Soapserializationenvelope object, do not forget to set the Bodyout property of the Soapsoapserializationenvelope class, which is the Soapobject object created in the first step.

Note:

The version number of the SOAP protocol can be from the WebService WSDL document (in this case "Http://192.168.0.121/testAndroidCall/WebService1.asmx?WSDL")

(4) Create a Httptransportsse object. You can specify the URL of the WSDL document for the WebService by using the Httptransportsse class's construction method:

Httptransportse ht=New Httptransportse (Web_service_url);

Web_service_url refers to the address of webservice, such as "http://192.168.0.121:80/testAndroidCall/WebService1.asmx?wsdl"

(5) using the call method to invoke the WebService method, code:

Ht.call (null, envelope);

The first parameter of the call method is generally null, and the 2nd parameter is the Soapserializationenvelope object created in step 3rd.

(6) using the GetResponse method to obtain the return result of the WebService method, the code:

soapprimitive result = (soapprimitive) envelope.getresponse ();

(7) Finally, attach the complete Callwebservice () method

/*** Call WebService * *@returnreturn value of WebService **/     PublicString Callwebservice (String MethodName, map<string, string>Params) {        //1. Specify the namespace of the WebService and the method name of the callSoapobject Request=NewSoapobject (Namespace, MethodName); //2, set the parameter value of the calling method, if there are no parameters, can be omitted,        if(Params! =NULL) {Iterator iter=Params.entryset (). iterator ();  while(Iter.hasnext ()) {Map.entry Entry=(Map.entry) iter.next ();            Request.addproperty (String) Entry.getkey (), (String) entry.getvalue ()); }        }        //3. Generate SOAP request information that calls the WebService 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 (Web_service_url); //To invoke the WebService method by using the call method        Try{Ht.call (NULL, envelope); } Catch(httpresponseexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Catch(xmlpullparserexception e) {e.printstacktrace (); }        Try {            Finalsoapprimitive result =(soapprimitive) envelope.getresponse (); if(Result! =NULL) {LOG.D ("----Replies received----", result.tostring ()); returnresult.tostring (); }        } Catch(SoapFault e) {LOG.E ("----An error occurred---", E.getmessage ());        E.printstacktrace (); }        return NULL; }
4. Running Code

To run the code in the article, first deploy WebService on IIS, and make sure that the Android phone's test program and WebService are on the same LAN.

Sample code

Android Side Source code

WebService source code

Related Article

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.