Skip to content

Latest commit

 

History

History
69 lines (56 loc) · 2.7 KB

README.md

File metadata and controls

69 lines (56 loc) · 2.7 KB

hattery

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 IOExceptions become IORExceptions
  • HttpRequests are immutable and thread-safe. You can pass them around anywhere.
  • Transports, while immutable and thread-safe, exist only to bootstrap HttpRequests. You probably don't want to pass them around in your code; instead pass around an empty HttpRequest.

Some extra features:

  • path() calls append to the url; url() calls replace the whole url.
  • Content-Type determines what is to be done with the body() and param()s (if either are present).
  • Unspecified Content-Type is inferred:
    • If there is a body(), application/json is assumed. Any param()s will become query parameters.
    • If POST() and no body(), application/x-www-form-urlencoded will be submitted
      • ...unless a BinaryAttachment parameter is included, in which case the content becomes multipart/form-data.
  • To run multiple async fetches concurrently with Google App Engine, use the AppEngineTransport and fetch() multiple HttpResponse objects. Getting the content of the response (say, via as()) completes the underlying asynchronous Future.