PROBLEM
Representation State Transfer (REST) is a lite-weight approach for communicating with other applications using HTTP and XML. While SOAP let’s you define your own operations, with REST services there are essentially only four operations: GET, POST, PUT and DELETE. Given it’s simplicity, REST services are becoming very popular building block on web applications.

SOLUTION
Since REST focusses on HTTP and XML, there isn’t a need for any specialized java libraries for accessing REST services. The JAVA platform already has the basic libraries in place for handling HTTP requests (java.net.* or org.apache.commons.httpclient.*) and processing XML (JAXP). Therefore nothing additional is required.

As far as consuming REST services from Spring applications, and in particular applications produced with Skyway Builder, the standard HTTP and XML processing logic available to java developers can be used. A developer can write java code and/or Spring beans for making the REST calls and processing the results. Additionaly a developer can leverage the Groovy support in Skyway.

HOW IT WORKS
Here’s an example java class that calls a REST service using Apache commons httpclient library.

Sample java code invoking REST services

/*
 * SampleWebServiceGet.java
 *
 * Created on September 12, 2009, 12:33 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package javaapplicationsimpletest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 *
 * @author Seven
 */
public class SampleWebServiceGet {
    
    public String callRestService(String request) throws IOException {
        
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(request);        
        
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        
        // Send GET request
        int statusCode = client.executeMethod(method);
        
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        
        byte[] responseBody = method.getResponseBody();
        
        return new String(responseBody);
    }
    
}


Note:
We need download “commons-httpclient, commons-logging, commons-codec” from apache.org

Advertisements