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
- The cURL to Code Converter
- Java 17 or later
Steps
Convert the command
Load the example: a PUT with a JSON body, a bearer token,
-Land--max-time 15. The converter builds a client that follows redirects with a 15-second connect timeout, and a request with the same timeout.Run it as a single file
Download
Main.javaand runjava Main.java. Java compiles and runs single files directly, so you can check the request before adding it to a project.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(); }Check the status
senddoesn’t throw for 4xx or 5xx responses. Checkresponse.statusCode()and handle errors before reading the body.
Try it yourself
Opens the cURL to Code Converter with this tutorial's sample loaded.
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: