Android Invoke Web Service (CXF) instance application detailed _android

Source: Internet
Author: User
Tags call back soap serialization xmlns tomcat server stringbuffer wsdl
Google provides support for the development of Web service for the Ndroid platform, providing ksoap2-android related rack packs
1. Download the package can be directly logged into the Http://code.google.com/p/ksoap2-android/, now the site has provided a direct download, as long as the download link can be downloaded;
My present is Ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar.

2. OK, now we can do a new project to test, first we set up a Java server, some of the preparation here I do not say (such as the integration of spring and other examples),
Since the focus here is on the Android client, the Java server side directly gives the code

Interface:(here are two methods, one passing is a simple string and the other is a conforming object + set.
Copy Code code as follows:

Package xidian.sl.service.webService;
Import Javax.jws.WebParam;
Import Javax.jws.WebService;
Import javax.jws.soap.SOAPBinding;
Import Javax.jws.soap.SOAPBinding.Style;
Import xidian.sl.service.impl.webService.StudentList;
@WebService
@SOAPBinding (style = Style.rpc)
Public interface Testservice {
public string GetUser (@WebParam (name = "name") string name);
Public studentlist getstulist ();
}

Implement:
Copy Code code as follows:

Package xidian.sl.service.impl.webService;
Import java.util.ArrayList;
Import java.util.List;
Import Javax.jws.WebService;
Import xidian.sl.entity.Students;
Import Xidian.sl.service.webService.TestService;
@WebService (endpointinterface = "Xidian.sl.service.webService.TestService")
public class Testserviceimpl implements Testservice {
@Override
public string GetUser (string name) {
SYSTEM.OUT.PRINTLN ("client-delivered name =" +name);
return name;
}
@Override
Public Studentlist getstulist () {
System.out.println ("This method is called");
list<students> stulist = new arraylist<students> ();
First Student
Students stu1 = new Students ();
Stu1.setstuname ("Shen Lang");
Stu1.setstunum ("1006010054");
Stu1.setstusex ("male");
Stulist.add (STU1);
A second student
Students STU2 = new Students ();
Stu2.setstuname ("fragrant incense");
Stu2.setstunum ("1006010043");
Stu2.setstusex ("female");
Stulist.add (STU2);
Encapsulate the list collection as an object for delivery in WebService
Studentlist studentlist = new Studentlist ();
Studentlist.setstulist (stulist);
return studentlist;
}
}

The package object of the list
Copy Code code as follows:

Package xidian.sl.service.impl.webService;
Import java.util.List;
Import xidian.sl.entity.Students;
public class Studentlist {
Private list<students> stulist;
Public list<students> getstulist () {
return stulist;
}
public void Setstulist (list<students> stulist) {
This.stulist = stulist;
}
}

The following configuration can then be made in the Srping consolidated configuration file (configured in the default web.xml)
Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xmlns:jaxws= "Http://cxf.apache.org/jaxws"
Xsi:schemalocation= "
Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context.xsd
Http://cxf.apache.org/jaxws
Http://cxf.apache.org/schemas/jaxws.xsd ">
<import resource= "Classpath:meta-inf/cxf/cxf.xml"/> <!--these XML files are Cxf-2.5.0.jar in the Meta-inf directory of-->
<!--<import resource= "Classpath:meta-inf/cxf/cxf-extension-soap.xml"/>
The warning prompt has abandoned the Cxf-extension-soap.xml file-->
<import resource= "Classpath:meta-inf/cxf/cxf-servlet.xml"/>
<!--here Configure the service interface, described later
ID: Refers to the ID of the bean that is configured in spring.
Implementor: Specifies the specific implementation class.
Address: Indicates the relative addresses of this Web service
-->
<!--test-->
<bean id= "Testserviceimpl" class= "Xidian.sl.service.impl.webService.TestServiceImpl" >
</bean>
<jaxws:endpoint id= "Testservice"
Implementor= "#testServiceImpl"
address= "/test"/>
<!--to open Tomcat server, Access http://localhost:8080/WebExam/services/test?wsdl
Http://localhost:8080/WebExam is the access address for this project
Services is derived from the Web.xml configuration, test is due to the address attribute in the spring configuration file
-->
</beans>

3. To this server side has been built completely, we can test under: Open Tomcat, and then enter HTTP://LOCALHOST:8090/WEBEXAM/SERVICES/TEST?WSDL in the browser to view the WSDL

Now we can start building Android clients.
When you create a new item and import Ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar, here's a special note: How to import a package do not choose the right key to the item---->build path---- >
Add External archives ..., if you use this method to appear to have imported the package, but there is no way to refer to, and then start the project will always report:

The way we choose and develop the Web is to create a new Lib or Libs folder under the project, and then copy the jar directly into that folder, and the IDE will help directly introduce:


This is the right thing to do, no longer report class cannot be referenced to the
Android in the WebService call server is actually very simple, as long as the step-by-step follow the following steps:
(1) Create the Httptransportse object that is used to invoke the WebService action

Copy Code code as follows:

Httptransportse ht = new Httptransportse (Service_url);

(2) Create Soapserializationenvelope objects
Copy Code code as follows:

Soapserializationenvelope envelope = new Soapserializationenvelope
(SOAPENVELOPE.VER11);

(3) Create a Soapobject object that needs to pass in the namespace and WebService method name of the Web service to be invoked when creating the object
Copy Code code as follows:

Soapobject request = new Soapobject (Service_ns, MethodName);

(4) If a parameter is passed to the Web service server side, the AddProperty (String name, object value) method of the Soapobject object is invoked to set the parameter, and the method's name parameter specifies the argument name
Attention: The parameter name does not have to be the same as the parameter name in the method of the service-side, as long as the corresponding order is the same; value parameter specified
Copy Code code as follows:

Request.addproperty ("name", "1006010054");

(5) Call the Soapserializationenvelope Setoutputsoapobject () method, or assign a value directly to the Bodyout property. Set the Soapobject object created in the first two steps to the outgoing SOAP message body of Soapserializationenvelope
Copy Code code as follows:

Envelope.bodyout = Request;

(6) Invoke the call () method of the object and invoke the remote Web service with Soapserializationenvelope as a parameter
Copy Code code as follows:

Ht.call (null, envelope);

(7) When the drop is completed, access to the Bodyin property of the Soapserializationenvelope object, which returns a Soapobject object that represents the return message of the Web service, resolves the object to obtain the call web return value of Service
Copy Code code as follows:

Soapobject result = (soapobject) Envelope.bodyin;
String name = Result.getproperty (0). toString ();

Here is a specific example of the book
Mian.xml is very simple is two edit box:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:orientation= "Vertical" >
<textview
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "@string/hello"/>
<edittext
Android:id= "@+id/edittext1"
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
Android:ems= "Ten" >
<requestfocus/>
</EditText>
<edittext
Android:id= "@+id/edittext2"
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
android:ems= "Ten"/>
</LinearLayout>

Activity: (The activity invokes a method that returns a normal string on the server side)
Copy Code code as follows:

Package xidian.sl.android.webservice;
Import Org.ksoap2.SoapEnvelope;
Import Org.ksoap2.serialization.SoapObject;
Import Org.ksoap2.serialization.SoapSerializationEnvelope;
Import Org.ksoap2.transport.HttpTransportSE;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.widget.EditText;
public class Webservicesimpledemo extends activity{
Final static String Service_ns = "http://webService.service.sl.xidian/";
Final static String Service_url = "Http://192.168.1.103:8090/WebExam/services/test";
Private EditText txt1;
Private EditText txt2;
/** called the activity is a. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Txt1 = (edittext) Findviewbyid (R.ID.EDITTEXT1);
Txt2 = (edittext) Findviewbyid (R.ID.EDITTEXT2);
The method called
String methodname = "GetUser";
Creating Httptransportse Transfer Objects
Httptransportse ht = new Httptransportse (Service_url);
Ht.debug = true;
To create a envelop object using the soap1.1 protocol
Soapserializationenvelope envelope = new Soapserializationenvelope (SOAPENVELOPE.VER11);
Instantiating a Soapobject object
Soapobject request = new Soapobject (Service_ns, MethodName);
/**
* Set parameters, the parameter name does not need to be the same as the calling server-side parameter names, only the corresponding order is required
* */
Request.addproperty ("name", "1006010054");
To set the Soapobject object as an outgoing SOAP message for a Soapserializationenvelope object
Envelope.bodyout = Request;
try{
Call WebService
Ht.call (null, envelope);
Txt1.settext ("Look" +envelope.getresponse ());
if (envelope.getresponse ()!= null) {
Txt2.settext ("There is return");
Soapobject result = (soapobject) Envelope.bodyin;
String name = Result.getproperty (0). toString ();
Txt1.settext ("return value =" +name);
}else{
Txt2.settext ("no Return");
}
}catch (Exception e) {
E.printstacktrace ();
}
}
}

Registering the activity in Androidmanifest.xml and adding access to the network
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Xidian.sl.android.webservice"
Android:versioncode= "1"
Android:versionname= "1.0" >
<USES-SDK android:minsdkversion= "Ten"/>
<application
android:icon= "@drawable/ic_launcher"
Android:label= "@string/app_name" >
<activity
Android:name= ". Webservicesimpledemo "
Android:label= "@string/app_name" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<!--Declare the permissions that the application owns-->
<uses-permission android:name= "Android.permission.INTERNET"/>
</manifest>

The results of the run are as shown in the figure:


Here we try to call back the method that conforms to the object:
Activity

Copy Code code as follows:

Package xidian.sl.android.webservice;
Import Org.ksoap2.SoapEnvelope;
Import Org.ksoap2.serialization.SoapObject;
Import Org.ksoap2.serialization.SoapSerializationEnvelope;
Import Org.ksoap2.transport.HttpTransportSE;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.widget.EditText;
public class Webservicecomplexdemo extends activity{
Final static String Service_ns = "http://webService.service.sl.xidian/";
Final static String Service_url = "Http://192.168.1.103:8090/WebExam/services/test";
Private EditText txt1;
Private EditText txt2;
/** called the activity is a. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Txt1 = (edittext) Findviewbyid (R.ID.EDITTEXT1);
Txt2 = (edittext) Findviewbyid (R.ID.EDITTEXT2);
The method called
String methodname = "Getstulist";
Creating Httptransportse Transfer Objects
Httptransportse ht = new Httptransportse (Service_url);
Ht.debug = true;
To create a envelop object using the soap1.1 protocol
Soapserializationenvelope envelope = new Soapserializationenvelope (SOAPENVELOPE.VER11);
Instantiating a Soapobject object
Soapobject request = new Soapobject (Service_ns, MethodName);
/**
* Set parameters, the parameter name does not need to be the same as the calling server-side parameter names, only the corresponding order is required
* */
Request.addproperty ("name", "1006010054");
To set the Soapobject object as an outgoing SOAP message for a Soapserializationenvelope object
Envelope.bodyout = Request;
try{
Call WebService
Ht.call (null, envelope);
Txt2.settext ("Return Value:" +envelope.getresponse ());
if (envelope.getresponse ()!= null) {
Soapobject result = (soapobject) Envelope.bodyin;
Soapobject soapchilds = (soapobject) result.getproperty (0);
StringBuffer sb = new StringBuffer ();
for (int i=0 i <soapchilds.getpropertycount (); i++) {
Soapobject soapchildschilds = (soapobject) soapchilds.getproperty (i);
Sb.append ("name [" +i+ "] =" +soapchildschilds.getproperty (0). toString () + "\ n");
Sb.append ("School Number [" +i+ "] =" +soapchildschilds.getproperty (1). toString () + "\ n");
Sb.append ("Sex [" +i+ "] =" +soapchildschilds.getproperty (2). toString () + "\ n" + "\ n");
}
Txt1.settext (Sb.tostring ());
}else{
Txt1.settext ("no Return");
}
}catch (Exception e) {
E.printstacktrace ();
}
}
}

The difference is that the return value of the processing, using several Getpropert () method, where the main look at the level of return values, see the following results should be clear, according to the level of brackets to determine

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.