Fork me on GitHub


Install With Maven:

        <!-- -->

<!-- -->

<!-- pick a JSON module if you want to parse JSON include one of these: -->
<!-- Google GSON -->

<!-- OR maybe you like Jackson better? -->

Upgrading from Previous Versions

See the Upgrade Guide


See the Change Log for recent changes.


So you’re probably wondering how using Unirest makes creating requests in Java easier, here is a basic POST request that will explain everything:

HttpResponse<JsonNode> response ="http://localhost/post")
      .header("accept", "application/json")
      .queryString("apiKey", "123")
      .field("parameter", "value")
      .field("firstname", "Gary")

Requests are made when as[Type]() is invoked, possible types include Json, String, Object Empty and File.

Route Parameters

Sometimes you want to add dynamic parameters in the URL, you can easily do that by adding a placeholder in the URL, and then by setting the route parameters with the routeParam function, like:

     .routeParam("fruit", "apple")

// Results in `http://localhost/apple`

The placeholder {fruit} will be replaced with apple.

The placeholder’s format is as easy as wrapping in curly braces: {custom_name}

All param values will be URL-Encoded for you

Default Base URLs

You can configure a default base URL to be used for all requests that do not contain a full URL.

This configuration will result in a GET to “”


Query Parameters

Query-string params can be built up one by one

                .queryString("fruit", "apple")
                .queryString("droid", "R2D2")

// Results in "http://localhost?fruit=apple&droid=R2D2"

Again all param values will be URL-Encoded.

You can also pass in query strings as arrays and maps:

        .queryString("fruit", Arrays.asList("apple", "orange"))
        .queryString(ImmutableMap.of("droid", "R2D2", "beatle", "Ringo"))

 // Results in "http://localhost?fruit=apple&fruit=orange&droid=R2D2&beatle=Ringo"


Request headers can be added with the header method.

            .header("Accept", "application/json")
            .header("x-custom-header", "hello")

Basic Authentication

Unirest exposes a shortcut for doing basic auth when you need to. Unirest handles the Base64 encoding part. Please make sure you are always doing this over HTTPS!

            .basicAuth("user", "password1!")

// this adds the header "Authorization: Basic dXNlcjpwYXNzd29yZDEh"

Body Data

Entity Bodies

You can post entity objects as the full body easily. This is the default behavior of most REST services.

Unless you specify otherwise the default Content-Type is text/plain; charset=UTF-8"http://localhost")
                .body("This is the entire body")

You can also post as a Object that is serialized using a configured ObjectMapper. (see Object Mappers for implementation details. Unirest comes with a default mapper that will serialize to json using the popular Google Gson library"http://localhost")
            .header("Content-Type", "application/json")
            .body(new SomeUserObject("Bob"))

// This will use Jackson to serialize the object into JSON.

JSON Patch Bodies

Unirest has full native support for JSON Patch requests (RFC-6902 see Per the spec, the default Content-Type for json-patch is application/json-patch+json

            .add("/fruits/-", "Apple")
            .replace("/lastname", "Flintstone")
            .test("/firstname", "Fred")
            .move("/old/location", "/new/location")
            .copy("/original/location", "/new/location")

will send a request with a body of


Basic Forms

Basic http name value body params can be passed with simple field calls. The Content-Type for this type of request is defaulted to application/x-www-form-urlencoded"http://localhost")
       .field("fruit", "apple")
       .field("droid", "R2D2")

  // This will post a simple name-value pair body the same as a HTML form. This looks like
  // `fruit=apple&droid=R2D2'

File Uploads

You can also post binary data in a form. Like a file.

The Content-Type for this type of request is defaulted to multipart/form-data"http://localhost")
       .field("upload", new File("/"))

For large files you may want to use a InputStream. Pass it a file name if you want one. We are using a FileInputStream here but it can actually be any kind of InputStream.

InputStream file = new FileInputStream(new File("/"));"http://localhost")
       .field("upload", file, "")

Upload Progress Monitoring

If you are uploading large files you might want to provide some time of progress bar to a user. You can monitor this progress by providing a ProgresMonitor.

                .field("upload", new File("/"))
                .uploadMonitor((field, fileName, bytesWritten, totalBytes) -> {
                    updateProgressBarWithBytesLeft(totalBytes - bytesWritten);

Asynchronous Requests

Sometimes, well most of the time, you want your application to be asynchronous and not block, Unirest supports this in Java using anonymous callbacks, or direct method placement. All request types also support async versions.

CompletableFuture<HttpResponse<JsonNode>> future ="http://localhost/post")
  .header("accept", "application/json")
  .field("param1", "value1")
  .field("param2", "value2")
  .asJsonAsync(response -> {
        int code = response.getStatus();
        JsonNode body = response.getBody();

Paged Requests

Sometimes services offer paged requests. How this is done is not standardized but Unirest proves a mechanism to follow pages until all have been consumed. You must provide two functions for extracting the next page. The first is to get the HttpResponse in the format you want, the other is to extract the next link from the response. The result is a PagedList of HttpResponse<T>. The paged list has some handy methods for dealing with the results. Here we are getting a paged list of Dogs where the next link is in the headers.

PagedList<Doggos> result =  Unirest.get("https://somewhere/dogs")
                        r -> r.asObject(Doggos.class),
                        r -> r.getHeaders().getFirst("nextPage")

Client Certificates

In case you need to use a custom client certificate to call a service you can provide unirest with a custom keystore. You may either pass a KeyStore object or a path to a valid PKCS#12 keystore file.

  .clientCertificateStore("/path/mykeystore.p12", "password1!");



Sometimes you need to tunnel through a proxy. Unirest can be configured to do this. Note that authenticated proxies cannot be configured on a per-request basis unless you want to build it into the URL itself.

    // Configure with authentication:
    Unirest.config().proxy("", 7777, "username", "password1!");

    // or without
    Unirest.config().proxy("", 7777);

    // or pass it in the request. This will override any proxy done in the config
    // currently only unauthenticated proxies work
                    .proxy("", 7777)


Unirest makes the actual request the moment you invoke of it’s as[type] method. These methods also inform Unirest what type to map the response to. Options are Empty, String, File, Object, byte and Json.

The response returns as a HttpResponse<T> where the HttpResponse object has all of the common response data like status and headers. The Body (if present) can be accessed via the desired type with the .getBody() method.

Empty Responses

If you aren’t expecting a body back, asEmpty is the easiest choice. You will still get back response information like status and headers.

HttpResponse response = Unirest.delete("http://localhost").asEmpty()

String Responses

The next easiest response type is String. You can do whatever you want with it after that.

String body = Unirest.get("http://localhost")

Object Mapped Responses

Most of the time when consuming RESTful services you probably want to map the response into an object.

For this you need to provide the Unirest configuration with a implementation of ObjectMapper (see Object Mappers for details.).

If the response is JSON you are in luck and Unirest comes with a basic JsonObjectMapper basic on Google GSON

Before an asObject(Class) it is necessary to provide a custom implementation of the ObjectMapper interface (if you do not wish to use the default mapper). This should be done only the first time, as the instance of the ObjectMapper will be shared globally.

Unirest offers a few plug-ins implementing popular object mappers like Jackson and Gson. See mvn central for details.

For example,

// Response to Object
Book book = Unirest.get("http://localhost/books/1")

// Generic types can be resolved by using a GenericType subclass to avoid erasure
List<Book> books = Unirest.get("http://localhost/books/")
			  .asObject(new GenericType<List<Book>>(){})

Author author = Unirest.get("http://localhost/books/{id}/author")
                       .routeParam("id", bookObject.getId())

Errors in Object or JSON parsing

You can’t always get what you want. And sometimes results you get from web services will not map into what you expect them to. When this happens with a asObject or asJson request the resulting body will be null, but the response object will contain a ParsingException that allows you to get the error and the original body for inspection.

UnirestParsingException ex = response.getParsingError().get();

ex.getOriginalBody(); // Has the original body as a string.
ex.getMessage(); // Will have the parsing exception.
ex.getCause(); // of course will have the original parsing exception itself.

Mapping Error Objects

Sometimes with REST API’s the service will return a error object that can be parsed. You can optionally map this into an POJO like

    HttpResponse<Book> book = Unirest.get("http://localhost/books/{id}")

    // This will be null if there wasn't an error
    Error er = book.mapError(Error.class);

    // You can also take advantage of this inside of the ifFailure method
           .ifFailure(Error.class, r -> {
                    Error e = r.getBody();

Mapping one body type to another without an object mapper

If you don’t want to provide a full ObjectMapper implementation you may use a simple function to map the response

    int body = Unirest.get("http://httpbin/count")

File Responses

Sometimes you just want to download a file, or maybe capture the response body into a file. Unirest can do both. Just tell Unirest where you want to put the file.

File result = Unirest.get("http://some.file.location/")

Download Progress Monitoring

If you are uploading large files you might want to provide some time of progress bar to a user. You can monitor this progress by providing a ProgresMonitor.

                .downLoadMonitor((b, fileName, bytesWritten, totalBytes) -> {
                    updateProgressBarWithBytesLeft(totalBytes - bytesWritten);

JSON responses

Unirest offers a lightweight JSON response type when you don’t need a full Object Mapper.

String result = Unirest.get("")

Large Responses

Some response methods (asString, asJson) read the entire response stream into memory. In order to read the original stream and handle large responses you can use several functional methods like:

   Map r = Unirest.get(MockServer.GET)
                .queryString("firstname", "Gary")
                .asObject(i -> new Gson().fromJson(i.getContentReader(), HashMap.class))

or consumers:

                .thenConsumeAsync(r -> {
                       // something like writing a file to disk

Error Handling

the HttpResponse object has a few handler methods that can be chained to deal with success and failure:

Putting them together might look like this:

                .ifSuccess(response -> someSuccessMethod(response))
                .ifFailure(response -> {
                    log.error("Oh No! Status" + response.getStatus());
                    response.getParsingError().ifPresent(e -> {
                        log.error("Parsing Exception: ", e);
                        log.error("Original body: " + e.getOriginalBody());


Unirest offers a simple im memory response caching mechanism with a few options for entry expiration. This can be either be enabled with defaults, with expiration options or consumers may supply a custom cache backed by the cache of their choice. It is reccomended that in high load systems consumers back the cache with a dedicated cache implementation like EHCache or Guava.

Basic cache:


     //These 1st response will be cached in this case:

Advanced Options:

You can use a builder to customize eviction rules:

               .depth(5) // Depth is the max number of entries cached
               .maxAge(5, TimeUnit.MINUTES)); // Max age is how long the entry will be kept.

Custom Caches

You can also supply a custom cache by implementing the Cache Interface

    public static void main(String[] args){
       Unirest.config().cacheResponses(Cache.builder().backingCache(new GuavaCache()));

    // Example backing cache using Guava
    public static class GuavaCache implements Cache {
  <Key, HttpResponse> regular = CacheBuilder.newBuilder().build();
  <Key, CompletableFuture> async = CacheBuilder.newBuilder().build();
            public <T> HttpResponse get(Key key, Supplier<HttpResponse<T>> fetcher) {
                try {
                    return regular.get(key, fetcher::get);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
            public <T> CompletableFuture getAsync(Key key, Supplier<CompletableFuture<HttpResponse<T>>> fetcher) {
                try {
                    return async.get(key, fetcher::get);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);


Previous versions of unirest had configuration split across several different places. Sometimes it was done on Unirest, sometimes it was done on Option, sometimes it was somewhere else. All configuration is now done through Unirest.config()

           .proxy(new Proxy("https://proxy"))
           .setDefaultHeader("Accept", "application/json")
           .addInterceptor(new MyCustomInterceptor());

Changing Unirest’s config should ideally be done once, or rarely. Once Unirest has been activated configuration options that are involved in creating the client cannot be changed without an explicit shutdown or reset.

Config Options

Builder Method Impact Default
connectTimeout(int) Sets the connection timeout for all requests in millis 10000
proxy(proxy) Sets a proxy object for negotiating proxy servers. Can include auth credentials  
setDefaultHeader(String, String) Sets a default header. Will overwrite if it exists  
setDefaultHeader(String, Supplier<String>) Sets a default header by supplier. Good for setting trace tokens for microservice architectures. Will overwrite if it exists  
addDefaultHeader(String, String) Adds a default header. Multiple for the same name can exist  
addDefaultHeader(String, Supplier<String>) Add a default header by supplier. Good for setting trace tokens for microservice architectures.  
setDefaultBasicAuth(String, String) Add a default Basic Auth Header  
followRedirects(boolean) toggle following redirects true
enableCookieManagement(boolean) toggle accepting and storing cookies true
cookieSpec(String) set a cookie policy. Acceptable values: ‘default’ (same as Netscape), ‘netscape’, ‘ignoreCookies’, ‘standard’ (RFC 6265 interoprability profile) , ‘standard-strict’ (RFC 6265 strict profile) default
automaticRetries(boolean) toggle disabling automatic retries (up to 4 times) for socket timeouts true
verifySsl(boolean) toggle enforcing SSL true
addShutdownHook(boolean) toggle to add the clients to the system shutdown hooks automatically false
clientCertificateStore(String,String) Add a PKCS12 KeyStore by path for doing client certificates  
clientCertificateStore(KeyStore,String) Add a PKCS12 KeyStore for doing client certificates  
connectionTTL(long,TimeUnit) Total time to live (TTL) defines maximum life span of persistent connections regardless of their expiration setting. No persistent connection will be re-used past its TTL value. -1
connectionTTL(Duration) Add total time to live (TTL) by Duration. Good for moderns Java APIs. -1
errorHandler(Consumer<HttpResponse<?>> consumer) Set a global error handler that will be invoked for any status > 400 or a parsing error  
interceptor(Interceptor value) Set a global Interceptor handler that will be invoked before and after each request  
defaultBaseUrl(String value) Set a default base URL to be used for all requests that do not already contain a scheme  

Global Interceptor

You can set a global interceptor for your configuration. This is invoked before and after each request. This can be useful for logging or injecting common attributes.

See for details.

Multiple Configurations

As usual, Unirest maintains a primary single instance. Sometimes you might want different configurations for different systems. You might also want an instance rather than a static context for testing purposes.

    // this returns the same instance used by Unirest.get("http://somewhere/")
    UnirestInstance unirest = Unirest.primaryInstance();
    // It can be configured and used just like the static context
    String result = unirest.get("http://foo").asString().getBody();

    // You can also get a whole new instance
    UnirestInstance unirest = Unirest.spawnInstance();

WARNING! If you get a new instance of unirest YOU are responsible for shutting it down when the JVM shuts down. It is not tracked or shut down by Unirest.shutDown();

Object Mappers

Unirest offers a few different Object Mapper’s based on popular JSON libraries (Jackson and GSON).



If you have some other need you can supply your own Object mapper by implementing the ObjectMapper interface. It has only a few methods


Unirest has hooks for collecting metrics on your runtime code. This is a simple and lightweight framework that marks two events:

  1. The moment just before the actual request is made
  2. The moment just after the actual request is made

Context information like method and request path are given to you so that you can collect based on whatever your needs are. In its simplest form it might look like this:

   Unirest.config().instrumentWith(requestSummary -> {
              long startNanos = System.nanoTime();
              return (responseSummary,exception) ->"path: {} status: {} time: {}",
                      System.nanoTime() - startNanos);

By providing more feature rich UniMetric instances you could easily calculate averages per route, uptime, or other fun facts.

Shutting Down

Unirest starts a background event loop and your Java application won’t be able to exit until you manually shutdown all the threads by invoking:


Once shutdown, using Unirest again will re-init the system