The HTTP client

java.net.http.HttpClient is in the JDK since Java 11, so an HTTP call needs no library at all: a client, a request with a method and a body, and a response handler that says what to do with the answer. A request is built once and may be sent many times, and a client is meant to be shared by the whole program.

A request, a response and a status

The program starts a small HTTP server from the JDK on a free local port, calls it three times and stops it. The port is ephemeral and is never printed, so the output is the same on every machine and the example needs no network:

http.scala

import com.sun.net.httpserver.{HttpExchange, HttpServer} import java.net.{InetSocketAddress, URI} import java.net.http.{HttpClient, HttpRequest, HttpResponse} def reply(exchange: HttpExchange, status: Int, body: String): Unit = val bytes = body.getBytes("UTF-8") exchange.getResponseHeaders.add("Content-Type", "text/plain; charset=utf-8") exchange.sendResponseHeaders(status, bytes.length.toLong) val out = exchange.getResponseBody out.write(bytes) out.close() @main def http(): Unit = val server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0) server.createContext("/health", exchange => reply(exchange, 200, "ok")) server.createContext( "/echo", exchange => reply(exchange, 200, new String(exchange.getRequestBody.readAllBytes(), "UTF-8")) ) server.start() try val port = server.getAddress.getPort val base = s"http://127.0.0.1:$port" val client = HttpClient.newHttpClient() val health = HttpRequest.newBuilder(URI.create(s"$base/health")).GET().build() val response = client.send(health, HttpResponse.BodyHandlers.ofString()) println(response.statusCode()) println(response.body()) println(response.headers().firstValue("content-type").orElse("none")) val post = HttpRequest .newBuilder(URI.create(s"$base/echo")) .header("Content-Type", "text/plain") .POST(HttpRequest.BodyPublishers.ofString("ping")) .build() val echoed = client.send(post, HttpResponse.BodyHandlers.ofString()) println(echoed.body()) val missing = HttpRequest.newBuilder(URI.create(s"$base/missing")).GET().build() println(client.send(missing, HttpResponse.BodyHandlers.ofString()).statusCode()) finally server.stop(0)

scala-cli run --server=false http.scala

200
ok
text/plain; charset=utf-8
ping
404

BodyHandlers.ofString() turns the body into a String; ofByteArray and ofFile are the other two a program uses for a download. firstValue("content-type") answers an Optional because a header may be missing, which is the Java type Scala reads with orElse. The last call asks for a path the server does not have and reads the status instead of the body: 404 is an answer, not an exception.

What changes against a real service

Against a service on the network, the URI is the only part of the program that must change: https instead of http, a host name instead of the loopback address, and a port only when it is not the default. The client sends a GET or a POST the same way, follows the redirects it is configured to follow, and a timeout is set on the request builder with timeout so that a server which never answers cannot hold the program.

Two details matter in a real client. The call send blocks until the response arrives, so it belongs on a pool of its own or in a future, and sendAsync returns a CompletableFuture for the same call without blocking. And the body of a failed request is still worth reading: a 400 usually explains in its body what was wrong with the request.

Related

Article author: Arthur Isaev