Hattery (mad, of course) is a Java library for making HTTP requests. It provides a simple fluent interface based around immutable objects.
Hattery includes two transports. DefaultTransport
uses HttpURLConnection
; AppEngineTransport
uses the asynchronous urlfetch service and allows multiple requests to operate in parallel.
// Typically start with an empty request, no need to hold on to the transport
HttpRequest request = new DefaultTransport().request();
// A GET request
Thing thing1 = request
.url("http://example.com/1")
.param("foo", "bar")
.fetch().as(Thing.class);
// A POST request
Thing thing2 = request
.url("http://example.com/2")
.POST()
.param("foo", "bar")
.fetch().as(Thing.class);
// Some extra stuff you can set
List<Thing> things3 = request
.url("http://example.com")
.path("/3")
.header("X-Whatever", "WHATEVER")
.basicAuth("myname", "mypassword")
.param("foo", "bar")
.timeout(1000)
.retries(3)
.mapper(new MySpecialObjectMapper())
.fetch().as(new TypeReference<List<Thing>>(){});
Install with maven:
<dependency>
<groupId>com.voodoodyne.hattery</groupId>
<artifactId>hattery</artifactId>
<version>look up the latest version number</version>
</dependency>
Some philosphy:
- Checked exceptions are a horrible misfeature of Java. Only runtime exceptions are thrown; all
IOException
s becomeIORException
s HttpRequest
s are immutable and thread-safe. You can pass them around anywhere.Transport
s, while immutable and thread-safe, exist only to bootstrapHttpRequest
s. You probably don't want to pass them around in your code; instead pass around an emptyHttpRequest
.
Some extra features:
path()
calls append to the url;url()
calls replace the whole url.POST()
submits the content asapplication/x-www-form-urlencoded
, unless aBinaryAttachment
parameter is included, in which case the content becomesmultipart/form-data
.- To run multiple async fetches concurrently with Google App Engine, use the
AppEngineTransport
andfetch()
multipleHttpResponse
objects. Getting the content of the response (say, viaas()
) completes the underlying asynchronousFuture
.