Details about android web service calling (cxf) instance applications

Source: Internet
Author: User

Google provides support for the development of Web Service for the ndroid platform, and provides the Ksoap2-android
1. You can directly log on to the supervisor to download the package;
My current is ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar

2. now, we can create a new project for testing. First, we should set up a java Server. I will not talk about some preparations here (for example, examples of integration with spring ),
Because the focus here is on the android client, the java Server directly gives the code

Interface(Two methods are provided here, one passing a simple string, and the other passing an object + set)Copy codeThe Code is 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 codeThe Code is 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 ("the name passed by the client is =" + name );
Return name;
}
@ Override
Public StudentList getStuList (){
System. out. println ("this method is called ");
List <Students> stuList = new ArrayList <Students> ();
// The first student
Students stu1 = new Students ();
Stu1.setStuName ("Shen Lang ");
Stu1.setStuNum ("1006010054 ");
Stu1.setStuSex ("male ");
StuList. add (stu1 );
// The second student
Students stu2 = new Students ();
Stu2.setStuName ("Xiangxiang ");
Stu2.setStuNum ("1006010043 ");
Stu2.setStuSex ("female ");
StuList. add (stu2 );
// Encapsulate the List set into an object before it can be passed in webService.
StudentList studentList = new StudentList ();
StudentList. setStuList (stuList );
Return studentList;
}
}

List encapsulated objectCopy codeThe Code is 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;
}
}

Then, configure the following in the srping integration configuration file (the default web. xml file has been configured)Copy codeThe Code is 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. xml"/> <! -- These xml files are in the cxf-2.5.0.jar directory of the META-INF -->
<! -- <Import resource = "classpath: META-INF/cxf/cxf-extension-soap.xml"/>
Warning prompt that the cxf-extension-soap.xml file has been discarded -->
<Import resource = "classpath: META-INF/cxf/cxf-servlet.xml"/>
<! -- Configure the service interface here, which is described later
Id: the bean ID configured in spring.
Implementor: Specifies the specific implementation class.
Address: Specifies the relative Address of the web service.
-->
<! -- Test -->
<Bean id = "testServiceImpl" class = "xidian. sl. service. impl. webService. TestServiceImpl">
</Bean>
<Jaxws: endpoint id = "testService"
Implementor = "# testServiceImpl"
Address = "/test"/>
<! -- Enable the tomcat server to access http: // localhost: 8080/WebExam/services/test? Wsdl
Http: // localhost: 8080/WebExam is the access address of this project.
Services is obtained by web. xml configuration, and test is obtained by the address attribute in the Spring configuration file.
-->
</Beans>

3. The server has been fully established. We can test: Enable tomcat, and enter http: // localhost: 8090/WebExam/services/test in the browser? View the wsdl

Now we can start to build the android client.
After creating a project, import the ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar. Note: Do not right-click the project to import the package ----> build path ---->
Add external archives... if you use this method, it seems that the package has been imported, but it still cannot be referenced. After the project is started, the following message is reported:

We chose the same method as web development, that is, to create a lib or libs folder under the project, and then copy the jar directly to the folder. IDE will help introduce it directly:


In this way, the error message is no longer reported that the class cannot be referenced.
In android, it is still very easy to call the server through webservice, as long as you follow the steps below:
(1) Create an HttpTransportSE object, which is used to call WebService operations

Copy codeThe Code is as follows: HttpTransportSE ht = new HttpTransportSE (SERVICE_URL );

(2) create a SoapSerializationEnvelope objectCopy codeThe Code is as follows: SoapSerializationEnvelope envelope = new SoapSerializationEnvelope
(SoapEnvelope. VER11 );

(3) create a SoapObject object. When creating this object, you must input the namespace and WebService Method Name of the Web Service to be called.Copy codeThe Code is as follows: SoapObject request = new SoapObject (SERVICE_NS, methodName );

(4) If a parameter is sent to the Web Service server, call the addProperty (String name, Object value) method of the SoapObject Object to set the parameter. The name parameter of this method specifies the parameter name.
Note:: The parameter name does not have to be the same as the parameter name in the server method, as long as the corresponding order is the same; value parameter specifies the parameter valueCopy codeThe Code is as follows: request. addProperty ("name", "1006010054 ");

(5) Call the setOutputSoapObject () method of SoapSerializationEnvelope, or directly assign values to the bodyOut attribute to set the SoapObject object created in the previous two steps to the outgoing SOAP message body of SoapSerializationEnvelope.Copy codeThe Code is as follows: envelope. bodyOut = request;

(6) call the call () method of the object and call the remote web service using SoapSerializationEnvelope as the parameterCopy codeThe Code is as follows: ht. call (null, envelope );

(7) after the disconnection is completed, access the bodyIn attribute of the SoapSerializationEnvelope object. This attribute returns a SoapObject object, which indicates the Response Message of the Web service and resolves the object, you can obtain the returned value of the web service call.Copy codeThe Code is as follows: SoapObject result = (SoapObject) envelope. bodyIn;
String name = result. getProperty (0). toString ();

The following is an example of a specific book.:
Mian. xml has two editing boxes:Copy codeThe Code is 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 = "10">
<RequestFocus/>
</EditText>
<EditText
Android: id = "@ + id/editText2"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: EMS = "10"/>
</LinearLayout>

Activity :( this Activity calls the server side to return a normal string)Copy codeThe Code is 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 when the activity is first created .*/
@ 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 );
// Call Method
String methodName = "getUser ";
// Create an httpTransportSE transmission object
HttpTransportSE ht = new HttpTransportSE (SERVICE_URL );
Ht. debug = true;
// Use the soap1.1 protocol to create an Envelop object
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope (SoapEnvelope. VER11 );
// Instantiate a SoapObject object
SoapObject request = new SoapObject (SERVICE_NS, methodName );
/**
* Set the parameter. The parameter name does not necessarily need to be the same as the parameter name on the called server, but only needs to be in the same order.
**/
Request. addProperty ("name", "1006010054 ");
// Set the SoapObject object to the outgoing SOAP message of the SoapSerializationEnvelope object
Envelope. bodyOut = request;
Try {
// Call webService
Ht. call (null, envelope );
// Txt1.setText ("look" + envelope. getResponse ());
If (envelope. getResponse ()! = Null ){
Txt2.setText ("Returned ");
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 ();
}
}
}

Register Activity in AndroidManifest. xml and add network access permissions.Copy codeThe Code is 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" type = "codeph" text = "/codeph">
<Uses-sdk android: minSdkVersion = "10"/>
<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 of the application itself -->
<Uses-permission android: name = "android. permission. INTERNET"/>
</Manifest>

Result After running:


Next we will try to call the method for returning objects that meet the requirements:
Activity:

Copy codeThe Code is 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 when the activity is first created .*/
@ 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 );
// Call Method
String methodName = "getStuList ";
// Create an httpTransportSE transmission object
HttpTransportSE ht = new HttpTransportSE (SERVICE_URL );
Ht. debug = true;
// Use the soap1.1 protocol to create an Envelop object
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope (SoapEnvelope. VER11 );
// Instantiate a SoapObject object
SoapObject request = new SoapObject (SERVICE_NS, methodName );
/**
* Set the parameter. The parameter name does not necessarily need to be the same as the parameter name on the called server, but only needs to be in the same order.
**/
/Request. addProperty ("name", "1006010054 ");
// Set the SoapObject object to the outgoing SOAP message of the SoapSerializationEnvelope object
Envelope. bodyOut = request;
Try {
// Call webService
Ht. call (null, envelope );
Txt2.setText ("returned 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 ("student ID [" + I + "] =" + soapChildsChilds. getProperty (1). toString () + "\ n ");
Sb. append ("gender [" + 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 getPropert () method is used for processing the returned value. Here we mainly look at the returned value level. We should be able to see the following results and determine them based on the brackets.

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.