14 Consuming Web Services Example 1 – TUTORIAL – Android Application 14 The WebServiceCall class negotiates the transporting of request/response objects as well as preparation of serial
Trang 1Android
Consuming Web Services
Using KSOAP (on IIS) and REST (on Apache Tomcat)
18C
Victor Matos
Cleveland State University
Notes are based on:
Android Developers
http://developer.android.com/index.html
Trang 22
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.
Trang 33
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
Trang 44
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 )
Trang 55
Consuming Web Services
5
Web Services
Trang 66
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)
Trang 77
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
Trang 88
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
Trang 99
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:
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
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
Trang 11Consuming Web Services Example 1 – TUTORIAL – IIS Server Side Code
Android App accessing
all services available
at the IIS server
Trang 12
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
Trang 13Consuming Web Services Example 1 – TUTORIAL – Android Application
A fragment of the Main class follows
// 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
Trang 1414
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 )
private static final String SOAP_ACTION = "http://tempuri1.org/" ;
private static final String NAMESPACE = "http://tempuri1.org/" ;
private static final String URL =
"http://iamok.somee.com/MathService.asmx" ;
protected Object call( String soapAction,
SoapSerializationEnvelope envelope)
{
Trang 15Consuming Web Services Example 1 – TUTORIAL – Android Application
WebServiceCall class (continuation 2/4)
Object result = null ;
final HttpTransportSE transportSE = new HttpTransportSE( URL );
transportSE debug = false ;
// call and Parse Result
Trang 1616
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){
// 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 =
envelope dotNet = true ;
// place in envelope the outgoing request object
envelope.setOutputSoapObject(requestObject);
Trang 17Consuming Web Services Example 1 – TUTORIAL – Android Application
The WebServiceCall class (continuation 4/4)
try
{
// call webmethod and parse returning response object
final Object response = (Object) this call(
Trang 1818
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]
Trang 19Consuming Web Services Example 1 – TUTORIAL – IIS Server Side Code
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
public class EnglishDistance implements KvmSerializable {
private int _feet ;
private int _inches ;
Trang 20this _feet = Integer.parseInt(obj.getProperty( "feet" ).toString());
}
public String showDistance(){
return _feet + "\" " + _inches + "\' " ;
Trang 21Consuming Web Services Example 1 – TUTORIAL – IIS Server Side Code
Transferring Complex Data Objects to/from Server ( 3 of 5 )
@Override
public Object getProperty( int index) {
Object object = null ;
return object;
}
Needed by interface
Trang 23Consuming Web Services Example 1 – TUTORIAL – IIS Server Side Code
Transferring Complex Data Objects to/from Server ( 5 of 5 )
Trang 2424
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;
Trang 25Consuming Web Services Example 1 – TUTORIAL – IIS Server Side Code
Transferring Data Objects Server Definition 2/2
public String ShowEnglishDistance() {
return _feet + "\" " + _inches + "\' ";
}
{
get { return this._feet; }
set { _feet = value; }
Trang 2626
Consuming Web Services Example 1 – TUTORIAL – Android Code
26
Android – Sending / Receiving Objects from Web Services ( 1 of 3)
This fragment is from the Android’s app Main class It creates an instance of an EnglishDistance and sends it to the server to be increased by half a foot
Transferring of the object requires its serialization
// make a local EnglishDistance object & pass it to webservice
// get the modified object back from service (6 more inches)
EnglishDistance ed1 = new EnglishDistance(6, 16);
txtMsg append( "\nMake ED ed1= " + ed1.showDistance() );
EnglishDistance ed2 = (EnglishDistance)webServiceCall.AddHalfFoot(ed1);
Trang 27Consuming Web Services Example 1 – TUTORIAL – Android Code
Android – Sending / Receiving Objects from Web Services ( 2 of 3)
This fragment is from the Android’s app WebServiceCall class It prepares the
request object and its EnglishDistance object parameter, calls the service and picks the returned object
public EnglishDistance AddHalfFoot(EnglishDistance inputEd){
// indicate webservice (endpoint) to be called
final String webMethod = "AddHalfFoot" ;
// Create the outgoing request object
final SoapObject requestObject = new SoapObject( NAMESPACE , webMethod);
// add outgoing parameter (name-type) must agree with endpoint
requestObject.addProperty( "inputEd" , inputEd);
// Create soap envelope for IIS server
final SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope. VER11 );
envelope dotNet = true ;
Trang 2828
Consuming Web Services Example 1 – TUTORIAL – Android Code
28
Android – Sending / Receiving Objects from Web Services ( 3 of 3)
This fragment is from the Android’s app WebServiceCall class It prepares the
request object and its EnglishDistance object parameter, calls the service and picks the returned object
// call webservice and parse returning response object
EnglishDistance outputEd = null ;
final Object response = this call( SOAP_ACTION + webMethod, envelope );
Trang 30Consuming Web Services Example 2 – TUTORIAL – Android Code
HttpServletRequest: the request object
Represents a client's request This object gives a servlet access to incoming information such as HTML form data and HTTP request headers
HttpServletResponse: the response object
Represents the servlet's response The servlet uses this object to return data
to the client such as HTTP errors (200, 404, and others), response headers (Content-Type, Set-Cookie, and others), and output data by writing to the response's output stream or output writer
Trang 31Consuming Web Services Example 2 – TUTORIAL – Android Code
REST Protocol – Android & Apache Server
Trang 32
Use the container login mechanism configured for the ServletContext to authenticate the user
making this request
Trang 33Consuming Web Services Example 2 – TUTORIAL – Android Code
REST Protocol – Android & Apache Server
Returns any extra path information after the servlet name but before the query string, and
translates it to a real path
getQueryString()
Returns the query string that is contained in the request URL after the path
getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the
user has not been authenticated
getRequestedSessionId ()
Returns the session ID specified by the client
Trang 34Gets the AsyncContext that was created or reinitialized by the most recent invocation of startAsync() or
startAsync(ServletRequest,ServletResponse) on this request
getAttribute(java.lang.String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists
Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales
that are acceptable to the client based on the Accept-Language header
getLocalName()
Returns the host name of the Internet Protocol (IP) interface on which the request was received
Trang 35Consuming Web Services Example 2 – TUTORIAL – Android Code
REST Protocol – Android & Apache Server
Reference: http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html
Interface ServletRequest
getLocalPort()
Returns the Internet Protocol (IP) port number of the interface on which the request was received
getParameter(java.lang.String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist
getParameterMap()
Returns a java.util.Map of the parameters of this request
getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request
getParameterValues(java.lang.String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter
does not exist
getProtocol()
Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for
example, HTTP/1.1
getReader()
Retrieves the body of the request as character data using a BufferedReader
getRealPath(java.lang.String path)
Deprecated As of Version 2.1 of the Java Servlet API, use ServletContext#getRealPath instead
Trang 36Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS
removeAttribute(java.lang.String name)
Removes an attribute from this request
setAttribute(java.lang.String name, java.lang.Object o)
Stores an attribute in this request
setCharacterEncoding(java.lang.String env)
Overrides the name of the character encoding used in the body of this request
startAsync()
Puts this request into asynchronous mode, and initializes its AsyncContext with the original (unwrapped)
ServletRequest and ServletResponse objects
startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
Puts this request into asynchronous mode, and initializes its AsyncContext with the given request and response
objects