cURL to Code Converter · Tutorial

How to call a REST API from Java with HttpClient

8 min readintermediateUpdated

An API’s docs show how to update a customer with curl. You will convert the command to plain Java with no libraries, run it straight away, and refactor it into a method you can call from your application.

What you need

Steps

  1. Convert the command

    Load the example: a PUT with a JSON body, a bearer token, -L and --max-time 15. The converter builds a client that follows redirects with a 15-second connect timeout, and a request with the same timeout.

  2. Run it as a single file

    Download Main.java and run java Main.java. Java compiles and runs single files directly, so you can check the request before adding it to a project.

  3. Reuse one client

    Move the client into a field and the request into a method that takes the customer ID and the JSON. HttpClient is thread-safe and keeps connections open, so create it once.

    private static final HttpClient CLIENT = HttpClient.newBuilder()
            .followRedirects(HttpClient.Redirect.NORMAL)
            .build();
    
    static String updateCustomer(long id, String json) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.example.com/v1/customers/" + id))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + System.getenv("API_TOKEN"))
                .PUT(HttpRequest.BodyPublishers.ofString(json))
                .build();
        return CLIENT.send(request, HttpResponse.BodyHandlers.ofString()).body();
    }
  4. Check the status

    send doesn’t throw for 4xx or 5xx responses. Check response.statusCode() and handle errors before reading the body.

Try it yourself

Opens the cURL to Code Converter with this tutorial's sample loaded.

Try it now

Common mistakes

Expecting redirects to be followed
Without followRedirects, HttpClient returns 301 and 302 responses as they are. Add it when the curl command uses -L; the converter does this for you.
Creating a new client for every request
Each new client opens new connections, which is slow. Share one instance.

Next steps

Go back to the cURL to Code Converter, or keep going with one of these: