Tải bản đầy đủ (.pdf) (66 trang)

Android chapter18c Consuming Web Services Using KSOAP (on IIS) and REST (on Apache Tomcat)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.03 MB, 66 trang )

Android
Consuming Web Services
Using
KSOAP (on IIS) and REST (on Apache Tomcat)

18C
Victor Matos
Cleveland State University

Notes are based on:
Android Developers

2 2 2
18C. Android - Internet Web Services

Consuming Web Services

2
Web Services
• Support machine-to-machine collaboration.

• They can be described, published, located, and invoked over a
data network.

• Web services are used to implement the notion of a service-
oriented architecture (SOA).

SOA applications are independent of specific programming languages
or operating systems.

• Web services rely on existing transport technologies, such as


HTTP, and XML, for invoking the implementation.



3 3 3
18C. Android - Internet Web Services

Consuming Web Services

3
Web Services

The interface describing the format of services can be done using
the Web Services Description Language (WSDL).

According to W3C there are two major types of web services

• REST-compliant which use XML to represent its Web
resources, and offers a "stateless" set of operations; and

• Arbitrary solutions, in which the service may expose a
heterogeneous set of operations.





4 4 4
18C. Android - Internet Web Services


Consuming Web Services

4
Web Services - Implementations
Two widely used architectures supporting Web services are

Representational State Transfer (REST) Closely tie to the HTTP protocol by
associating its operation to the common GET, POST, PUT, DELETE for HTTP.

Remote Procedure Call (RPC). Web services are directly implemented as
language-specific functions or method calls. In this category we find
1. Object Management Group's (OMG) Common Object Request Broker
Architecture (CORBA),
2. Microsoft's Distributed Component Object Model (DCOM) and
3. Sun Microsystems's Java/Remote Method Invocation (RMI).







5 5 5 5
18C. Android - Internet Web Services

Consuming Web Services

5
Web Services



















6 6 6
18C. Android - Internet Web Services

Consuming Web Services

6
How Android Applications Consume WebServices?

We will present two examples of how an Android application can
request services hosted in a

(1) IIS webserver (RPC discrete function oriented approach)


(2) Apache-Tomcat 7.0 (REST state oriented approach)


The examples are exhaustive and include details of how the
server-side methods are constructed (you may skip this portion
based on your previous experience)



7 7 7
18C. Android - Internet Web Services

Consuming Web Services

7
Example 1 - How .NET Web Services Are Called?
Services are passive server-side pieces of code waiting for
incoming messages to do some work. Clients initiate the interaction
by sending a message to server-services requesting action.

Services expose one or more endpoints where messages can be
sent. Each endpoint consists of
address (where to send messages)
binding (how to send messages )
contract (what messages contain)

Clients can use WSDL to know this information before accessing a
service.





8 8 8
18C. Android - Internet Web Services

Consuming Web Services

8
Example 1 - How .NET Web Services Are Called?
Windows Communication Foundation (WCF) uses the information
found in the service contract to perform dispatching and
serialization.

Dispatching is the process of deciding which method to call for
an incoming SOAP message.

Serialization is the process of mapping between the data found
in a SOAP message and the corresponding .NET objects used in
the method






9 9 9
18C. Android - Internet Web Services

Consuming Web Services


9
Example 1 - How .NET Web Services Are Called?
Our example code consists of two fragments which implement the
server and client side of the application.

Server Side:
The document describes how
to create a simple Web service running on a Windows IIS-Server. We
have chosen to expose our collection of methods on the free host
www.somee.com.

Client Side:
We use the KSOAP 2.0 platform to request a sequence of remote
procedure calls to the IIS server hosting our service code. The methods
include functions taking zero, or more simple/object-complex inputs that
return simple/object-complex results.


10 10 10
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

10
Services Available at the IIS Server



11 11 11

18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

11
Android App accessing
all services available
at the IIS server



12 12 12
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – Android Application
12
Our Android app uses KSOAP 2 API. KSOAP is a webservice client
library for constrained Java environments. SOAP protocol is widely
used for machine-to-machine interaction, it is strong-typed and
supports synchronous, asynchronous, and complex-routing
communication schemes.

Our implementation includes three classes

1. Main webcalls are assembled
2. EnglishDistance (Serialized)
3. WebServiceCall deals with HTTP
transporting of the

request/response
and envelope objects



13 13 13
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – Android Application
13
A fragment of the Main class follows
public class Main extends Activity {
public TextView txtMsg;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtMsg = (TextView)findViewById(R.id.txtMsg);

WebServiceCall webServiceCall = new WebServiceCall();

// add two numbers - get int result
int intResult = webServiceCall.AddService(11, 22);
txtMsg.append( "\nAdd RESULT= " + intResult );
}

All the intelligent work is done by the WebServiceCall class.
14 14 14

18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – Android Application
14
The WebServiceCall class negotiates the transporting of request/response objects as well
as preparation of serialization of complex data elements ( 1/4 )
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.util.Log;

public class WebServiceCall
{
private static final String SOAP_ACTION = "
private static final String NAMESPACE = "
private static final String URL =
"

protected Object call( String soapAction,
SoapSerializationEnvelope envelope)
{

15 15 15
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – Android Application

15
WebServiceCall class (continuation 2/4)
Object result = null;

final HttpTransportSE transportSE = new HttpTransportSE(URL);

transportSE.debug = false;

// call and Parse Result.
try
{
transportSE.call(soapAction, envelope);
result = envelope.getResponse();

} catch (final Exception e)
{
Log.e("<<Exception>>",e.getMessage());
}
return result;
}

16 16 16
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – Android Application
16
Fragment of the WebServiceCall class called to add two numbers. Here input parameters
and output values resulting from the webservice are sent and received. (cont. 3/4)
public int AddService(int v1, int v2){


int intResult = 0;
// indicate webservice (endpoint) to be called
final String webMethod = "Add";

// Create the outgoing request message
final SoapObject requestObject = new SoapObject(NAMESPACE,
webMethod);
// add outgoing parameters (name-type must agree with endpoint)
requestObject.addProperty("v1", v1);
requestObject.addProperty("v2", v2);

// Create soap envelope for .NET server
final SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;

// place in envelope the outgoing request object
envelope.setOutputSoapObject(requestObject);
17 17 17
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – Android Application
17
The WebServiceCall class (continuation 4/4)

try
{
// call webmethod and parse returning response object

final Object response = (Object) this.call(
SOAP_ACTION + webMethod,
envelope);
if (response != null)
intResult = Integer.parseInt(response.toString());

} catch (Exception e)
{
Log.e("<<Exception-Add>>",e.getMessage());
}

return intResult;
}

}
Web
service is
called here
18 18 18
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

18
Transferring Complex Data Objects to/from Server
The previous fragment illustrates the sending of simple pieces of
primitive data (int, strings, …) between client and server.

When complex objects are exchanged the sender and receiver

must deal with the serialization of the objects in transit.

Serializing requires the client’s Java definition of the class to
implement the KvmSerializable interface. The server must also
mark the corresponding class as [Serializable].







19 19 19
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

19
Transferring Complex Data Objects to/from Server ( 1 of 5)
In the following fragment an EnglishDistance class is defined in the client (Java)
and server (C#). The following fragments of Android code illustrates the defining
of the class and the calling mechanism to send/receive this complex data type.










// Calling DotNET Webservices running on an IIS server
// This class represents a KvmSerializable version of an
// EnglishDistance(fett, inches). Observe the required
// methods: getProperty, setProperty, getPropertyCount.
// Author: Victor Matos - April 2011

package ucr.dotnetwebservices;

import java.util.Hashtable;

import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

public class EnglishDistance implements KvmSerializable {
private int _feet;
private int _inches;

20 20 20
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

20
Transferring Complex Data Objects to/from Server ( 2 of 5 )











public EnglishDistance(int feetValue, int inchesValue){
_feet = feetValue;
if (inchesValue >= 12) {
_feet += (int)(inchesValue / 12);
_inches = inchesValue % 12;
}
}

public EnglishDistance (SoapObject obj)
{
this._feet = Integer.parseInt(obj.getProperty("feet").toString());
this._inches = Integer.parseInt(obj.getProperty("inches").toString());
}

public String showDistance(){
return _feet + "\" " + _inches + "\' ";
}

@Override
public int getPropertyCount() {
return 2;
}


Needed by interface
21 21 21
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

21
Transferring Complex Data Objects to/from Server ( 3 of 5 )









@Override
public Object getProperty(int index) {
Object object = null;
switch (index)
{
case 0:
{
object = this._feet;
break;
}
case 1:

{
object = this._inches;
break;
}
}
return object;
}

Needed by interface
22 22 22
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

22
Transferring Complex Data Objects to/from Server ( 4 of 5 )









@Override
public void getPropertyInfo(int index, Hashtable hashTable,
PropertyInfo propertyInfo) {
switch (index)

{
case 0:
{
propertyInfo.name = "feet";
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
break;
}
case 1:
{
propertyInfo.name = "inches";
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
break;
}

}

Needed by interface
23 23 23
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

23
Transferring Complex Data Objects to/from Server ( 5 of 5 )











}//getProperty
@Override
public void setProperty(int index, Object obj) {
switch (index)
{
case 0:
{
this._feet = Integer.parseInt(obj.toString());
break;
}
case 1:
{
this._inches = Integer.parseInt(obj.toString());
break;
}

}

}//setProperty

}//EnglishDistance

Needed by interface
24 24 24
18C. Android - Internet Web Services


Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

24
Transferring Data Objects - .NET Code – IIS Server Definition 1/2
The following fragment shows the Server side definition of the EnglishDistance
class. Notice the server needs to agree with the client’s definition on attributes
(name, type); however it does not need to include the same methods.








namespace MathService
{
[Serializable]
public class EnglishDistance {
private int _feet = 0;
private int _inches = 0;

public EnglishDistance() {
_feet = 0; _inches = 0;
}

public EnglishDistance(int feet, int inches)
{

this._feet = feet; this._inches = inches;
if (inches >= 12) {
this._feet += (int)(inches / 12);
this._inches += (inches % 12);
}
}
25 25 25
18C. Android - Internet Web Services

Consuming Web Services
Example 1 – TUTORIAL – IIS Server Side Code

25
Transferring Data Objects. Server Definition 2/2








public String ShowEnglishDistance() {
return _feet + "\" " + _inches + "\' ";
}

public int feet
{
get { return this._feet; }
set { _feet = value; }

}

public int inches
{
get { return this._inches; }
set {
if (value >= 12)
{
this._feet += (int)(value / 12);
}
this._inches = (value % 12);
}
}

}//EnglishDistance
}

×