Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Rep Power

    Default Tutorial:Review of REST Web Services for the Web Service Developer Exam I

    In this article, we will look at REST Web Services looking at characteristics for REST Web services.We will also cover JSON Web Services and make comparisons between these two types of Web services and SOAP web services. This is part of a larger series of articles to help you prepare for the web service developer exam. You can review the articles on JAX-WS based Web Services, “Tutorial:Review of JAX-WS Client-Side Web Services for the Web Service Developer Exam”, “Tutorial:Review of JAX-WS Client-Side Web Services for the Web Service Developer Exam II”, “Tutorial:Review of JAX-WS Server-Side Web Services for the Web Service Developer Exam” and “Tutorial:Review of JAX-WS Server-Side Web Services for the Web Service Developer Exam II”, if needed.

    What is REST?

    REpresentation State Transfer (REST) originated with one man Roy Fielding who identified specific architectural principles when he was trying to answer a set of questions related to his doctoral thesis, “Architectural Styles and the Design of Network-based Software Architectures”. These questions were:
    1. Why is the Web so prevalent and ubiquitous?
    2. What makes the Web scale?
    3. How can I apply the architecture of the Web to my own applications.

    REST is the set of architecture principles that he discovered to respond to these questions. They are defined as:
    • Address resources key abstraction of information and data in REST is a resource, and each resource must be addressable via a URI (Uniform Resource Identifier).
    • A uniform, constrained interface Use a small set of well-defined methods to manipulate resources.
    • Representation-oriented the interaction that you have with services using representations of that service. A resource referenced by one URI can have different formats. Different platforms need different formats such as HTML for browsers, or JavaScript for JavaScript Object Notation (JSON) or XML possibly for a Java application.
    • Communicate stateless The easiest applications to scale are stateless applications.
    • Hypermedia As The Engine Of Application State (HATEOAS) meaning let the data format drive the state transitions in your applications.

    Fielding stated that REST-based architectures are those that communicate primarily through the transfer of representations of resources. This contrasts with the approach of Remote Procedure Call (RPC) which is based on the notion of invoking a procedure on the remote server. RPC messages contain information about the procedure to be invoked or the action to be taken. The procedure or action is referred to as a verb in a Web service request. With REST model, there are only a couple of verbs used for all actions. These are GET, POST, PUT, and DELETE. RPC will generally have many operations that are invoked from the same URI whereas REST operations will have a unique URI for each resource.

    The limited number of actions represented by a couple of verbs and the unique URI for each resource are two of the basic principles of REST. RESTful systems extend on these principles to encompass how shopping cart data is managed on the server as well as the maintenance of a session for the shopping process through the use of a cart. JAX-WS provides XML/HTTP Binding that is used for implementing RESTful services that provide session management capabilities using cookies, URL rewriting, and SSL session IDs.

    Another deviation from Fielding’s classic definition of REST is the use of embedded verbs and parameters inside URLs in order to get the constraint of the “uniform interface”. An example of this is’s REST interface which includes verbs in query strings and lacks unique URIs for each resource. Although this system is labeled as RESTful, they act more like RPC using XML over HTTP without SOAP. Below is a table that shows the key differences between the RESTful and SOAP Approach to Web Services:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-restful-soapwebservice.jpg
    Table: RESTful vs SOAP Web Services

    Note that REST uses simple XML over HTTP without a WSDL interface definition which contrasts with SOAP that does require a WSDL and can use a multitude of transport protocols for the XML within a SOAP envelope.

    RESTful Verb Use

    As we previously mentioned a key characteristics of a RESTful Web service is the explicit use of verbs that are directly related to HTTP methods as specified in HTTP 1.1. For example, a HTTP GET request is defined as a data-producing method that's to be used to retrieve a resource, fetch data from a Web server, or execute a query on the Web server that will respond with a set of matching resources.

    With REST, developers use HTTP methods explicitly and in a manner consistent with the protocol definition. The core REST design principle is to establish a one-to-one mapping between create, read, update, and delete (i.e. CRUD) operations and the corresponding HTTP methods. The mapping for REST operations is shown in the following table:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-rest-httpoperations.jpg
    Table: HTTP Operations for Manipulating Resources

    If developers were to use the HTTP methods in a manner consistent with the HTTP 1.1/RFC for identifying one specific resource or in the query string in a request URI includes a set of parameters that defines the search criteria used by the server to find a set of matching resources then that would be all well and good since these are all consistent with REST operations. Unfortunately many web APIs use most of the HTTP methods in ways for which they were not intended. For example there are some web APIs that use HTTP GET to trigger an update or insert of records into a database within a transactional context on the server. In the cases the GET request URI is not used in a RESTful manner. When those cases where the Web API uses GET to invoke remote procedures, it looks like the following:
    XML Code: HTTP GET Method
    GET /adduser?name=Peter HTTP/1.1
    In the listing above, the Web method is shown to support a state-changing operation using HTTP GET. This means that the HTTP GET request has side effects When the HTTP GET request is successful, it adds a new user to the underlying data store. All Web servers are designed to process HTTP GET requests by retrieving resources matching the path or the query criteria in the request URI and then returning these as part of the response. HTTP GET requests are not designed to add or update a record in a database. This is wholly inconsistent with the intended use of the protocol method as described in the specification for HTTP1.1 and for HTTP/1.1-compliant Web servers.

    Another problem noted in some web APIs for cases where an HTTP GET request is used for triggering the deletion, modification, or addition of a database record or even some server-side state change is that this will often invite crawlers and search engines to do unintentional server side changes by crawling a link. The workaround for this is to move the parameter names and values on the request URI into XML tags. You can then send the XML tags in the body of an HTTP Post where it will be a XML representation of the entity to create whose request URI is the intended parent of the entity. This is shown in the listings below:

    GET Request with Side Effects:
    XML Code: HTTP GET Request With Side Effects
    GET /adduser?name=Peter HTTP/1.1
    POST Request without Side Effects:
    XML Code: HTTP POST without Side Effects
    POST /users HTTP/1.1
    Host: acmeserver
    Content-Type: application/xml
    <?xml version="1.0"?>
    The second listing shows the proper use of HTTP POST in order to make a RESTful request. The payload is included in the body of the request. For the web server, the request is now processed by adding the resource contained within the body as a ancillary to the resource identified in the request URI. For a HTTP POST, the new resource can be added as a child of /users. This type of relationship between the new entity and its parent in the POST request is similar to the relationship between a new file and its parent directory. It is the client that defines the relationship between the entity and its parent as well as the new entity's URI in the POST request. The client application will obtain a representation of the resource via the new URI. This is shown in the listing below where we place the resource under /users:

    XML Code: GET Request with desired resource under /resources
    GET /users/Peter HTTP/1.1
    Host: acmeserver
    Accept: application/xml
    This is the proper way to use GET as it is being used specifically for data retrieval. There should never be any side effects from a GET operation. This quality of no side effects is known as idempotence.

    If you wanted to do an update operation using a HTTP GET, you would need to do a similar refactoring since once again this is not consistent with it’s intended use. The problematic request is shown in the listing below:

    XML Code: Using HTTP GET for Updates
    GET /updateuser?name=Robert&newname=Bob HTTP/1.1
    This type of request will change the name attribute of the resource. You can use query string in such an operation but as any type of query as string operation becomes more complex tends to break down and can possibly have a number of side effects. The best practice is to focus on using explicitly the HTTP methods for a RESTful approach. In this case, it would be an HTTP PUT request for updating the request rather than using HTTP GET. The HTTP PUT request is shown in the listing below:

    XML Code: Using HTTP PUT for updates
    PUT /users/Robert HTTP/1.1
    Host: acmeserver
    Content-Type: application/xml
    <?xml version="1.0"?>
    Again as in the use of the POST operation, using PUT request shown in the listing instead of the GET operation for the update provides a cleaner interface consistent with REST's principles as well as the definition of HTTP methods. The reason is that the PUT request explicitly identifies the resource to be updated in the request URI as well as transferring a new representation of the resource to the server in the body of the client’s PUT request. In the GET request, the resource attributes were a loose set of parameter names and values on the request URI. The listing above serves to rename the resource from Peter to Pete which also changes the URI to /users/Pete. In a REST Web service, any requests to an old URI after the PUT request has been successfully completed for the resource will generate a standard 404 NOT FOUND response.

    REST guidelines state that when using HTTP methods explicitly use nouns in URIs instead of verbs. For a RESTful Web service, the verbs such as POST, GET, PUT, and DELETE are already defined by the protocol. This allows you to maintain a general interface that facilitate clients being explicit about the operations they invoke. In general, RESTful Web services should not define more verbs or remote procedures, such as /adduser or /updateuser. The general design principle applies to the body of an HTTP request as well. This is intended to be used to transfer resource state. not to carry the name of a remote method or remote procedure to be invoked. You should not use it to carry the name of a remote method or remote procedure to be invoked.

    The Power of Stateless REST Web Services

    REST Web services that run in production environments must meet the requirements of the organizations that use them. That means they need to be scaleable, resilient with acceptable response times. In order to achieve this, infrastructure architects will design the service topology using clusters of servers with load-balancing and failover capabilities, proxies, and gateways in a manner that allows requests to be moved from one server to the other when required to decrease the overall response time of a Web service call. In order to use intermediary servers for scaleability, REST Web service clients must send requests that include all required data needed for fulfilling the request in order that intermediary servers are able to forward, route, and load-balance without the need to hold state information between requests.

    When a request is whole complete and independent, there is no need for the server to hold or retrieve neither state information nor the application context. REST clients provide HTTP headers and body in the request that have all the parameters, context and data needed for the Web service to generate the appropriate response. This ability to process business logic without holding any state improves Web service performance and simplifies the design and implementation of server-side components because the absence of state on the server removes the need to synchronize session data with an external application. In the case of a stateful design, the service will hold some sort of conversation state across multiple invocations of the Web Service. This is shown in the figure below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-statefulwebservices.jpg
    Figure: Stateful Web Service

    The figure shows a stateful web service where the client can page through a set of results. This assumes that the Web service keeps track of where the application leaves off while navigating the set. The Web service increments and stores a previousPage variable in order to be able to respond to requests for the next page. Stateful services can easily become complex. They require a lot of design upstream in order to store and enable the synchronization of session data across a cluster of Java EE containers. This problem is similar to synchronization problems with Enterprise JavaBeans (EJBs) or servlets and JavaServer Pages (JSPs). A problem that developers often confront is the dreaded during session replication. It can easily cost developers days or even an entire week in trying to determine the source of the problem (i.e. the object that doesn’t implement the Serializable interface) within a complex domain model and application services which are the basis of the server’s state. Also session synchronization add significant overhead that often has a deleterious effect on server performance.

    This is compare to stateless server-side components which are less complicated to design, write, and distribute across load-balanced servers. A stateless service will always perform better since maintaining client state is now the responsibility of the client application. The collaboration between client application and service is essential to being stateless in a RESTful Web service. It improves the performance by conserving bandwidth and minimizing the server-side application state. RESTful Web services are always responsible for generating and providing the interface that the client will use to maintain it’s own application state. If we transform the previous figure into one where application state is maintained on the client then for the request for a multipage result set, the client would hold the actual page number to retrieve instead of simply asking for next page. This is shown in the design below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-statelesswebservices.jpg
    Figure: Stateless Web Service

    In the figure above, the stateless Web service generates a response linking to the next page number in the set and provides the client with the information it needs in order to maintain this conversation with the server. One can break down this aspect of RESTful Web service design into a high-level separation of responsibilities clarifying how the stateless Web service is maintained. It is the following:
    • Server - generates responses including links to other resources that allow applications to navigate between related resources. Links are embedded in these type of responses. Also a typical RESTful response could include links to the parent’s children or subordinate in order that they remain connected in cases where the request is for a parent or container resource. The server is able to generate responses indicating if the information can be cached in order to improve performance. This is done in order to reduce the number of requests for the same resources as well as eliminating some requests entirely. The server includes a Cache-Control and Last-Modified date value in the HTTP response header in order to accomplish this.
    • Client application - this uses the Cache-Control response header to determine whether the resource should be cached. The client also checks the Last-Modified response header, copies the data value into a If-Modified-Since header to send back to the server in order to determine whether the resource has changed. sends back the date value in an to ask the server if the resource has changed. This is known as a Conditional GET. The server compare the two headers and if the resource has not been modified, it will return a 304 code response (i.e. Not Modified). When the server responds with a 304 HTTP response code, the client can safely use a cached, local copy of the resource representation as it is the most up-to-date version of the information. This has the effect of bypassing subsequent GET requests until the resource changes. The client application sends complete requests which are serviceable independently of other requests. This means the client is required to make full use of HTTP headers specified by the Web service interface and to send complete representations of resources in the request body. The client sends requests that make very few assumptions about prior requests, the existence of a session on the server, the server's ability to add context to a request, or about application state that is kept in between requests.

    URIs for Directory like Structures

    When you work with REST Web Services, URLs are one of the key aspects of REST that a developer must thing about. This is because everything with REST is done through a URL. URL is an acronym for uniform resource locator. It’s purpose is to be used to locate a resource. A key thing to remember is that URLs are also URIs, or uniform resource identifiers. What this implies is that any given URL is used to both locate a resource as well as to identify a resource.

    That a URL locates a resource should seem natural. We know that a URL is a means of uniquely identifying a resource because no two resources can share the same URL. Interestingly there are many URLs that don’t locate or identify anything but instead make demands. These RESTless URLs are not used to identify a thing, they are instead used for some type of action to be taken. In the figure below is illustrated the kind of URL handled by the a RESTless URL:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-restlessurl.jpg
    Figure: RESTless URL

    The figure shows that this URL is not used neither for identifying nor locating a resource. Consistent with the action oriented nature of many RESTless URLs, this URL requests that the server display the Order. The last part of the URL is used to identify the specific order by the custNo query parameter. By contrast, RESTful URLs respect that HTTP is focused on resources. The figure below transforms the RESTless URL to be a RESTful URL:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-restfulurl.jpg
    Figure: RESTful URL

    This figure shows the client application addressing a resource. The URL determines how whether the REST Web service is seen as intuitive and can be used in ways that a designers can easily anticipate. REST Web service URL should always be intuitive and easy to guess. The URL then becomes a kind of self-documenting interface that requires little explanation or reference for a developer to understand what resources that it points to as well as being able to derive related resources. That is why with REST URLs, their structure should be straightforward, predictable, and easily understood.

    One thing that’s not clear about this URL is what it does. That’s because the URL doesn’t do any- thing. Rather, it identifies a resource. Specifically, it locates the resource that represents a Spittle object. What will be done with that resource is a separate matter—one for HTTP methods to decide (which we’ll look at in section 11.2.3).

    What makes the RESTful URL interesting is that its path is parameterized. Whereas the RESTless URL took its input from query parameters, the RESTful URL’s input is part of the URL’s path. To be able to handle requests for that kind of URL, we’ll need a way to write a controller’s handler method so that it can take input from the URL’s path.

    One of the key ways to achieve the usability level desired is to define directory structure-like URLs. A REST URL is hierarchical, rooted at a single path with subpaths branching from it exposing the service's main areas. This means that a URL is not merely a slash-delimited string, but a tree with numerous subordinate and superordinate branches connected at nodes.

    The URL both locates a resource and uniquely identifies that resource. It serves as both a URI as it does as a URL. This is different form the RESTless URL where the URL is generally used as a query parameter to identify the resource. With a RESTful URL the entire base URL identifies the resource.

    A RESTful URL has no query parameters at all. This doesn’t imply that query parameters are not a legal way to send information to the server, they instead provide guidance to the server in accessing the resource. They are not used to help identify a resource.

    Generally, RESTful URLs tend to be hierarchical. They are read from left to right, moving from a broad concept to the more precise resource. Below are examples of URLs at several levels:

    Here are a list of guidelines to use while designing the URI structure for a RESTful Web service:
    • Always hide any server-side scripting technology file extensions such as .jsp, .php, .asp. This allows you to port your service to another scripting technology without needing to change the URIs.
    • Always use lower case for your the REST URLs
    • Eliminate spaces by using hyphens or underscores instead
    • Avoid using query strings whenever possible.
    • Avoid using the 404 Not Found code if the request URI is for a partial path. Instead provide a default page or resource as a response.
    • REST URLs should always be static. The reason for this is that all changes in the resource or in the implementation of the service will not impact on the link. In other words, you will be able to bookmark This allows bookmarking as well as decoupling the resources encoded in the URLs from how the relationship is represented.

    XML Documents and Schemas

    When you are implementing a Service Oriented Architecture (SOA) component that consumes or provides either Enterprise Information System records or other records involves formatting the records that need to be exchanged as XML documents. We formalize this process by creating an XML Schema to represent the structure of an XML document for a particular record. An example of our record is shown below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-uivieworderrecord.jpg
    Figure: UI View of Order Record

    We use the structure shown in the user interface as the basis for creating an XML document for the order record. The record is divided into four sections containing the following data:
    • Order Number
    • Order Header
    • Order Items
    • Other Information

    The listing below shows the XML document corresponding to this record:

    XML Code: Order Record as XML
    <Order xmlns=""
          <SHORT_TEXT>Adidas Predator Mens Sz 12</SHORT_TEXT>
          <SHORT_TEXT>Tottenham FC Home Kit</SHORT_TEXT>
      <OrderText>Rush order</OrderText>
    We have used a couple of namespaces in this listing. The Order element is from the namespace Note that ACME Laboratories is the URL used by Acme Corporation for its corporate namespaces. We use namespaces as a means of interpreting all tags in the proper context. This is because documents can originate from different system but use the same tags (such as item). Namespaces allow us to know which version of the type we are using. Note that the document refers to a XML Schema that is used to validate the integrity of the XML document in a manner similar to the way that you can impose constraints on database. The schema and its location is shown in the following line:

    XML Code: XML Schema
    Note how the this attribute associates the order.xml file with the schema that has a reference to for the namespace to be used for interpreting the schema and the second is a location where the schema can be found. The listing below shows part of the orders.xsd:
    XML Code: Schema for Orders
    <schema targetNamespace=""
      xmlns:oms="" version="1.0"
      <element name="Orders" type="oms:OrdersType"/>
      <element name="Order" type="oms:OrderType"/>
      <complexType name="OrdersType">
          <element ref="oms:Order" maxOccurs="unbounded"/>
      <complexType name="OrderType">
          <documentation>A Customer Order</documentation>
          <element name="OrderKey">
    		Unique Sales Document Identifier
              <restriction base="string">
                <maxLength value="10"/>
          <element name="OrderHeader" type="oms:BUSOBJ_HEADER">
    		Order Header referencing customer, payment, sale organization information.
          <element name="OrderItems">
              <documentation>Items in the Order</documentation>
                <element name="item" type="oms:BUSOBJ_ITEM"
    Note how the schema is used to specify the formats and to restrict values for data. In the listing the orderKey element, which is the unique identifier for the sales document, can be only 10 characters in length. This is done by using a restriction element in the simple type definition of the orderKey definition. These are called facets. They provide an important data quality management tool for developing service oriented architecture that is based on Web services.

    Accessing a REST Service without Java Web Services

    A key characteristics of a RESTful Web service is the explicit use of HTTP methods in a way that follows the protocol defined for HTTP 1.1. The use of HTTP GET, for example, is stated as a data-producing method intended to be used by a client application to retrieve a resource, fetch data from a Web server, or execute a query. When the Web server responds to the request, it will look for and respond with a set of matching resources.

    Consider an example where an XML document from a RESTful Web service is accessed via an HTTP GET request. The client application would need to issue a HTTP GET, and then process the HTTP response stream containing the XML document. If we avoid using the JAX-WS and simply use the class to handle most of the work related to generating the HTTP GET and processing the response. The client would need to use the URL and HttpURLConnection classes in order to implement this. This is shown in the figure below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-webservicewojax-ws.jpg
    Figure: Web Service without JAX-WS Client

    In the figure the client is implemented in a class called GetNewOrders. As stated above it uses instances of the URL and HttpURLConnection classes to do the work. Below is shown how the classes work in order to implement the XML document download:
    The client uses the URL.openConnection() method to create an instance of HttpURLConnection to make a connection to the Web service’s URL.
    HttpURLConnection.connect() sends the HTTP GET request with the Web Service’s URL configured within the request
    The Web service receives and then processes the request and outputs the appropriate XML document as part of the HTTP response stream.
    The client uses the HttpURLConnection’s InputStream in order to read the HTTP response’s XML document.
    For a real SOA based application, the document would be parsed, transformed, and possibly forwarded to another component of the distributed application. The listing below shows the client-side code for issuing the HTTP GET request and receiving the XML document via the HTTP response. Note the String is used to construct the URL instance that is passed to the client as args[0]. It is only when the HttpULRConnection’s connect() method is invoked that the HTTP request sent. Before this, the setRequestMethod() is invoked to indicate that a GET request will be sent. This listing is shown below:

    Java Code: RESTful Web Service Client for Downloading XML Document
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
          ("Usage: java GetNewOrders <Web Service URL>");
        // Create the HTTP connection to the URL
        URL url = new URL(args[0]);
        HttpURLConnection con = 
          (HttpURLConnection) url.openConnection();
        // write the XML from the input stream to standard out
        InputStream in = con.getInputStream();
        byte[] b = new byte[1024];  // 1K buffer
        int result =;
        while (result != -1) {

    Accessing a REST Service with JWS

    If we now consumer a RESTful Web Service via the JAX-WS 2.0 API. The client uses the<T>7 interface to do most of the work. It will have the same role as the HttpURLConnection. The figure below demonstrates how a JAX-WS based client would work:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-webservicejax-ws.jpg
    Figure: Web Service with JAX-WS Client

    The figure shows how to interact with a RESTful Web service using a JAX-WS-based client. In this case, the class GetNewOrders is implemented using the class. The Service class provides a client interface to a Web service. It was originally introduced in JAX-RPC 1.0 and designed to represent a WSDL defined service. As RESTful services do not have WSDL representations, the Service API is not really well aligned for the needs of RESTful Web services. But this is how the JAX-WS API are designed.

    The Service is used to create an instance of<Source> enabling XML message-level interaction with the target Web service. The Dispatch class is the low-level JAX-WS 2.0 API that requires clients to construct messages by using XML directly instead of a higher-level binding such as JAXB 2.0 schema derived program elements. For REST proponents, this is the preferred programming paradigm of direct access to the XML request and response messages. The steps showing the execution of a JAX-WS based client of GetNewOrders is the following:
    1. The Service.addPort() method is used by the client to create a port within the Service instance in order to access the RESTful Web service.
    2. The Service.createDispatch() method is invoked to create an instance of Dispatch<Source>. This is a Dispatch instance that enables you to work with XML request/response messages as instances of javax.xml.transform.Source.
    3. The Dispatch.invoke() method is called in order to package the XML request in a manner consistent with the JAX-WS 2.0 HTTP Binding and send it to the RESTful service. The invoke() method waits for the response before returning.
    4. The RESTful Web service processes the HTTP GET and then sends an HTTP response including the XML.
    5. The invoke() method returns the response XML message as an instance of Source.

    The listing below shows how to implement the JAX-WS based Client of GetNewOrders.

    Java Code: JAX-WS based Client for RESTful Web Service
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
          ("Usage: java GetNewOrders <Web Service URL>");
        QName svcQName = new QName("http://sample", "svc");
        QName portQName = new QName("http://sample", "port");
        Service svc = Service.create(svcQName);
        svc.addPort(portQName, HTTPBinding.HTTP_BINDING, args[0]);
        Dispatch<Source> dis =
          svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
        Map<String, Object> requestContext = dis.getRequestContext();
        requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "GET");
        Source result = dis.invoke(null);
        try {
          .transform(result, new StreamResult(System.out));
        } catch (Exception e) {
          throw new IOException(e.getMessage());
    From the listing above, we see that it is not straightforward to apply the WSDL based Service API in a REST context. First you need to create QName instances for the Service instance and the “port” corresponding to the RESTful Web service. If this was a SOAP based Web service, the qualified names would correspond to the WSDL definitions for the wsdl:service and wsdl:port. In terms of a RESTful service, the QName instances are not needed to invoke the RESTful service but are required by the API.
    Note that the addPort() method takes a URI parameter defining the transport binding. This is specified as a JAX-WS 2.0 HTTP Binding type. We pass in HTTPBinding.HTTP_BINDING URI as the value. The default for the URI parameter is SOAP over HTTP. The final parameter passed to the addPort() method is the URL of the RESTful Web service. In our example we pass in the first argument of the application (i.e. args[0]).

    Once the port for the RESTful service has been added by the addPort() method, it can be used to create an instance of Dispatch<Source>. Source is passed as the type parameter to the createDispatch() method. The type of payload is specified as Service.Mode.PAYLOAD rather than Service.Mode.MESSAGE. As we are working in a REST scenario rather than SOAP, therefore there is no envelope to speak about, so PAYLOAD is the logical option.

    There are a number of valid type parameters for Dispatch outside of Source. You can also provide JAXB objects such as java.xml.soap.SOAPMessage, and javax.activation.DataSource. For example, the DataSource enables clients to work with MIME-typed messages. If we compare this implementation we can note the differences between the two implementations. This can be seen in the table below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam I-b9-httpurlconnection.jpg
    Table: Comparison of HttpURLConnection vs JAX-WS

    What the table shows is that the JAX-WS version provides a much richer interface, even in the simple REST scenario we have presented. In a RESTful service, a URL is provides an adequate representation. There is no associated WSDL to provide further definition of the service. The only other information required is in terms of the use of HTTP POST or HTTP GET.

    It is clear that the Dispatch interface is better suited for working with XML request/response rather than HttpURLConnection. This is because the invoke() method captures the request/response semantics of the HTTP Binding better than with the HttpURLConnection.connect() method and the Dispatch interface allows us to work directly with XML representations of Source rather than reading and writing streams.


    OK. That is it for part 1. In the next article we will continue look at REST Web Service with and without JAX-WS as well as XSLT and JAXP. See you then.
    Last edited by Java Exam; 03-07-2012 at 05:15 PM.

Similar Threads

  1. Replies: 0
    Last Post: 02-24-2012, 12:33 PM
  2. Replies: 0
    Last Post: 02-23-2012, 06:56 PM
  3. Replies: 0
    Last Post: 02-15-2012, 02:28 PM
  4. Replies: 0
    Last Post: 02-14-2012, 08:21 PM
  5. Replies: 0
    Last Post: 01-17-2012, 05:53 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts