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 as application/x-www-form-urlencoded
Thing thing2 = request
.url("http://example.com/2")
.POST()
.param("foo", "bar")
.fetch().as(Thing.class);
// A POST request with a JSON body
Thing thing3 = request
.url("http://example.com/3")
.POST()
.body(objectThatWillBeSerializedWithJackson)
.fetch().as(Thing.class);
// Some extra stuff you can set
List<Thing> things4 = request
.url("http://example.com")
.path("/4")
.path("andMore") // adds '/' between path elements automatically
.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.Content-Type
determines what is to be done with thebody()
andparam()
s (if either are present).- Unspecified
Content-Type
is inferred:- If there is a
body()
,application/json
is assumed. Anyparam()
s will become query parameters. - If
POST()
and nobody()
,application/x-www-form-urlencoded
will be submitted- ...unless a
BinaryAttachment
parameter is included, in which case the content becomesmultipart/form-data
.
- ...unless a
- If there is a
- 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
.