Java Reference
In-Depth Information
Client cl = ClientBuilder.newClient()
WebTarget target = cl.target('http://localhost:1234/people/3')
def resp = target.request().get(Response.class)
A Client instance is created from a ClientBuilder , which in turn leads to a Web-
Target . A GET request uses the get method, whose argument is the data type of the
returned object. This example is taken from a hypermedia test, shown in the next section.
In Groovy, the Groovy JDK makes GET requests trivial. Groovy adds the toURL method
to java.lang.String , which converts a String into an instance of
java.net.URL . The Groovy JDK also adds the getText method to java.net.URL .
Pulling information from the web can therefore be as simple as
String response = 'http://localhost:1234/people/3'.toURL().text
Making POST, PUT, and DELETE requests is done in Groovy the same way it's done in
Java, which isn't fun. Instead, client access is best done through a library.
OneofthemostpopularHTTPlibrariesistheopensourceApacheHTTPClientlibrary( ht-
tp://hc.apache.org/httpcomponents-client-ga/index.html ) , which is part of the Apache Ht-
tpComponents project.
Rather than show the details of that library I'd rather focus on the corresponding Groovy
project, HttpBuilder. The HttpBuilder project ( http://groovy.codehaus.org/modules/http-
builder/ ) follows the classic Groovy idiom: wrap a Java library and make it easier to use.
While the documentation on the website isn't bad, I recommend looking at the test cases in
the source code for guidance on how to use the API.
Like most cool projects, the source code ishosted at GitHub at https://github.com/jgritman/
httpbuilder . The API includes a convenient class for REST applications called RESTCli-
ent , which I used in the tests in this chapter. The corresponding test class, RESTClien-
tTests , shows how to access Twitter using all the standard HTTP verbs.
I used the RESTClient class in the PersonResourceSpec tests. The RESTClient
class has a constructor that takes two arguments, the base URL and a content type:
RESTClient client = new RESTClient(
'http://localhost:1234/', ContentType.JSON)
Search WWH ::




Custom Search