> Docs > Http Client

Http Client

Use HttpClient.send() to send a request and receive the response (asynchronously):

    Async<HttpResponse> send(HttpRequest request)

For example

HttpClient client = new HttpClient();

HttpRequest request = HttpRequest.toGet("https://example.com");

Async<HttpResponse> asyncRes = client.send( request );

Or use the convenience method doGet(absoluteUri)

Async<HttpResponse> asyncRes = client.doGet( "https://example.com" );

Features include - proxy, authentication, cookies, etc.

The HttpClient API is asynchronous, see Async Programming. To demonstrate:

Async<String> asyncBody = client
    .doGet( "https://example.com" )                     // Async<HttpResponse>
    .peek(response -> out.println(response.status()))
    .then(response -> response.bodyString(MAX_CHARS))   // Async<String>
    .peek(System.out::println)
    .finally_(client::close)
;

The response body must be closed to free the underlying connection. In the previous example, the response.bodyString() method will close the body upon completion; bodyBytes() would do the same.

An HttpClient should be closed eventually.

Synchronous Use

You may not care about Async API; you just want to use HttpClient in a traditional, synchronous way.

This can be done by the sync() method on Async actions, for example

HttpResponse response = client.doGet("https://example.com").sync();
System.out.println(response.status());

String body = response.bodyString(MAX_CHARS).sync();
System.out.println(body);

Of course, sync() blocks the current thread, therefore you should not do this in an async environment, like in an HttpHandler.

Form Submission

To submit a form to a server, you can populate a FormData, then convert it toRequest:

FormData form = new FormData("POST", "http://localhost:8080/upload")
    .param("title", "A Kitty")
    .file ("image", "cat.gif");

HttpRequest request = form.toRequest();

client.send(request);

Configuration

HttpClient configuration is done by HttpClientConf, typically in the builder pattern. For example,

HttpClient client = new HttpClientConf()
    .proxy("127.0.0.1", 8080)
    .trafficDump(System.err::print)
    .newClient();

See also