October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Build a REST API Client with Java HttpClient and Jackson

Learn the Java HttpClient and Jackson workflow for sending JSON requests, handling HTTP responses, and converting response bodies into Java objects.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Java’s built-in HttpClient to send the request and Jackson to convert Java objects to JSON and back. The example below uses Jackson 2.x with JDK 17 or later; keep Jackson’s dependency and imports on the same major version. Replace the illustrative endpoint and DTO fields with the API’s documented contract.

Choose a Java and Jackson version

This tutorial uses Jackson 2.x and its com.fasterxml.jackson package family. FasterXML lists a JDK 8 baseline for Jackson 2.x and a JDK 17 baseline for Jackson 3.x; Jackson 3 uses tools.jackson packages instead. The major versions have different packages and Maven coordinates, so do not mix Jackson 2 dependencies with Jackson 3 imports. FasterXML recommends Jackson 3 for new projects while describing 2.x as actively maintained. Confirm the current release and compatibility details in the Jackson project portal and the Jackson Databind repository.

Add the Jackson Databind dependency for the major version you choose. Maven coordinates and exact release numbers change; use the current version listed by the project rather than copying an unverified version number. The examples below show Jackson 2 imports and APIs.

Build the DTOs and JSON mapper

Jackson handles JSON conversion; it does not send HTTP requests. Define Java types that match the fields and shapes documented by the service. These records are illustrative—the endpoint may require different fields or a different response structure.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import com.fasterxml.jackson.databind.ObjectMapper;

record CreateItemRequest(String name) {}
record ItemResponse(String id, String name) {}

ObjectMapper mapper = new ObjectMapper();

Jackson Databind provides both data binding between JSON and Java values and a tree model for working with JSON without defining a DTO for every shape. Types such as Java time values or third-party classes may require additional modules or configuration; check the documentation for the Jackson version and types you use.

Create and reuse an HttpClient

Build one client and reuse it for requests with the same configuration. Oracle’s Java SE documentation says that an HttpClient is immutable after construction and can send multiple requests. A client typically manages its own connection pool, so constructing one per operation can prevent connection reuse.

import java.net.http.HttpClient;
import java.time.Duration;

HttpClient client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(10))
    .build();

The connection timeout applies while establishing a connection; it is not a substitute for a timeout on each request. Configure redirects, proxy, authenticator, or preferred protocol version on the client only when the application needs them. The available builder options are documented in Oracle’s Java SE 25 HttpClient API.

Serialize JSON and build the request

An HttpRequest holds request-specific details such as URI, method, headers, timeout, and body publisher. A body publisher supplies the bytes sent as the request body. For an API that accepts a JSON POST at the illustrative URL below, serialize the DTO to a string and publish that string as the body.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.net.URI;
import java.net.http.HttpRequest;
import java.time.Duration;

CreateItemRequest payload = new CreateItemRequest("Example item");
String json = mapper.writeValueAsString(payload);

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/items"))
    .timeout(Duration.ofSeconds(20))
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(json))
    .build();

The URI, method, headers, and JSON fields are examples, not a real service contract. Set Content-Type when sending JSON and use Accept only when it reflects what the endpoint supports. Oracle documents request-building options in the Java SE 25 HttpRequest API.

Send the request and handle the response

Every send operation needs a body handler, which determines how the response body is consumed. For ordinary JSON-sized responses, BodyHandlers.ofString() is straightforward. The blocking send call waits for a response; check the status before parsing the body as the expected success type.

import java.io.IOException;
import java.net.http.HttpResponse;

try {
    HttpResponse<String> response = client.send(
        request,
        HttpResponse.BodyHandlers.ofString()
    );

    int status = response.statusCode();
    if (status < 200 || status >= 300) {
        throw new IOException("API returned HTTP " + status + ": " + response.body());
    }

    ItemResponse item = mapper.readValue(response.body(), ItemResponse.class);
    System.out.println(item);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new RuntimeException("HTTP request was interrupted", e);
}

This example treats any non-2xx status as an error and includes the response body in the exception for illustration. In an application, handle status codes and error-body formats according to the service contract, and avoid exposing sensitive response content in logs. A completed HTTP exchange is not proof that the application operation succeeded: inspect the status, headers, and body as required by the API.

send can also fail with IOException, which the example allows to propagate. If a method catches InterruptedException and cannot propagate it, restoring the interrupt flag preserves the interruption signal for calling code. Keep transport failures, non-success HTTP statuses, and malformed JSON distinguishable so callers can respond appropriately.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose blocking, asynchronous, or streaming handling

Approach Control flow Body handling Use when
send with BodyHandlers.ofString() Blocks until a response is available Convenient for ordinary JSON-sized bodies The calling code is already synchronous
sendAsync Returns a CompletableFuture for asynchronous composition Depends on the body handler selected The surrounding control flow is asynchronous
Streaming body handler Depends on whether send or sendAsync is used Requires explicit consumption and, where applicable, closure or cancellation Streaming fits the payload size and resource-handling needs

Choose between send and sendAsync based on how the rest of the program is structured, not on a blanket assumption that one is faster. With asynchronous requests, dependent future stages that do not specify an executor may run on an executor or on the thread that completes the future, depending on timing. For streaming responses, read the body to exhaustion or close or cancel it as appropriate so resources can be reclaimed and orderly shutdown is not stalled. Oracle documents the asynchronous and body-handling APIs in the Java SE 25 HttpClient API and the Java SE 26 java.net.http package overview.

Adapt the client to the target API

The client above covers one JSON request and one JSON success response. Before using it against a real service, map its published API contract onto the request and response handling.

  • Authentication: supply the authentication mechanism and headers required by the API.
  • Status and errors: define which status codes count as success and how error bodies should be interpreted.
  • Pagination: follow the service’s documented pagination fields, links, or tokens rather than assuming one response contains all results.
  • Retries: make retry decisions based on the operation’s idempotency and the provider’s guidance; do not automatically retry every failure.
  • Generic responses: for arrays or other parameterized JSON types, use a type-aware Jackson mechanism for the chosen major version rather than assuming a raw collection type preserves its element type.

Jackson’s package names and coordinates differ between major versions, and version-specific APIs can change. Verify imports, dependency coordinates, and type-handling details against the documentation for the release you select.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.