Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Tooltip: Unirest - Lightweight HTTP Request Client Libraries

2015-09-11

There are a lot of HTTP libraries available in the Java universe like the Apache HttpClient library. Also Java provides the HttpURLConnection class as a standard on-board. They all have in common that I (and thats just my humble opinion ;)) don’t like them really because they feel like a way back in 2001.

So today I stumbled over unirest, a simple and lightweight HTTP request client library for Java ( and also other other languages like Ruby or C#). It’s simple and fluent API reminds me of the way you would do HTTP calls in JavaScript.

I’ve taken two examples from the unirest website.

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .field("parameter", "value")
  .field("foo", "bar")
  .asJson();

Simple and stylish. There is also a serialisation available, although I’m using GSON and don’t need it.

// Only one time
Unirest.setObjectMapper(new ObjectMapper() {
    private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
                = new com.fasterxml.jackson.databind.ObjectMapper();

    public <T> T readValue(String value, Class<T> valueType) {
        try {
            return jacksonObjectMapper.readValue(value, valueType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String writeValue(Object value) {
        try {
            return jacksonObjectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
});

// Response to Object
HttpResponse<Book> bookResponse = Unirest.get("http://httpbin.org/books/1")
.asObject(Book.class);
Book bookObject = bookResponse.getBody();

HttpResponse<Author> authorResponse = Unirest.get("http://httpbin.org/books/{id}/author")
    .routeParam("id", bookObject.getId())
    .asObject(Author.class);

Author authorObject = authorResponse.getBody();

// Object to Json
HttpResponse<JsonNode> postResponse = Unirest.post("http://httpbin.org/authors/post")
        .header("accept", "application/json")
        .header("Content-Type", "application/json")
        .body(authorObject)
        .asJson();