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.
Example 3.1. Sample java code invoking REST services
import java.io.*; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; public class SampleWebServiceGet { public String callRestService(String request) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(request); // Send GET request int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } InputStream rstream = null; // Get the response body rstream = method.getResponseBodyAsStream(); // Process the response BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); String line; while ((line = br.readLine()) != null) { } br.close(); return line; } }
The following snippet of Groovy code is used to call a REST service.
Example 3.2. Sample Groovy code invoking REST services
"http://www.myapp.com/service/REST/get".toURL().text
RELATED RECIPES