Convert curl commands to Java code - Generate ready-to-use Java HttpClient code for API requests
// Java HttpClient code will appear here // Example: import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); String jsonBody = "{\"name\": \"test\"}"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); } }
Here are some common curl commands that you can convert to Java code:
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' https://api.example.com/users
curl -X PUT -H "Authorization: Bearer token123" -d '{"status":"active"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
curl -H "X-API-Key: abc123" -H "Accept: application/json" https://api.example.com/data
Java's HttpClient library (introduced in Java 11) is a powerful and modern way to make HTTP requests. Here are some common Java HttpClient patterns:
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileUploadExample { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .build(); Path path = Paths.get("document.pdf"); String boundary = "----WebKitFormBoundary" + System.currentTimeMillis(); String contentType = "multipart/form-data; boundary=" + boundary; // Create multipart form data String data = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + path.getFileName() + "\"\r\n" + "Content-Type: application/pdf\r\n\r\n"; byte[] fileData = Files.readAllBytes(path); byte[] requestBody = new byte[data.getBytes().length + fileData.length + ("\r\n--" + boundary + "--\r\n").getBytes().length]; System.arraycopy(data.getBytes(), 0, requestBody, 0, data.getBytes().length); System.arraycopy(fileData, 0, requestBody, data.getBytes().length, fileData.length); System.arraycopy(("\r\n--" + boundary + "--\r\n").getBytes(), 0, requestBody, data.getBytes().length + fileData.length, ("\r\n--" + boundary + "--\r\n").getBytes().length); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/upload")) .header("Content-Type", contentType) .header("Authorization", "Bearer YOUR_TOKEN_HERE") .POST(HttpRequest.BodyPublishers.ofByteArray(requestBody)) .build(); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } }
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class ErrorHandlingExample { public static void main(String[] args) { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(5)) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .timeout(Duration.ofSeconds(5)) .GET() .build(); try { HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); int statusCode = response.statusCode(); if (statusCode >= 200 && statusCode < 300) { System.out.println("Success: " + response.body()); } else { System.out.println("Error: " + statusCode + " - " + response.body()); } } catch (IOException e) { System.out.println("Connection error: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("Request interrupted: " + e.getMessage()); Thread.currentThread().interrupt(); } catch (Exception e) { System.out.println("Error making request: " + e.getMessage()); } } }
Copy your curl command → Paste into the input box → Get converted Java HttpClient code
Our converter supports complex curl commands and translates them to clean, efficient Java code using the HttpClient library
Our tool handles these common curl options and converts them to appropriate Java HttpClient code:
A: The generated Java HttpClient code requires Java 11 or higher. For older Java versions, consider using alternative HTTP clients like Apache HttpClient or OkHttp.
A: The basic generated code includes try/catch blocks for IOException and InterruptedException. For production code, you may want to add more specific error handling for different HTTP status codes.
A: The HttpClient library provides several BodyHandlers for processing responses. Use HttpResponse.BodyHandlers.ofString() for text responses, ofInputStream() for binary data, or ofByteArray() for raw bytes.
A: No external libraries are required. The HttpClient is part of the Java standard library since Java 11. For JSON processing, you might want to add a library like Jackson or Gson.
A: For file uploads in Java, you'll need to use multipart form data with HttpClient. Our converter handles curl commands with -F
or --form
options and generates the appropriate Java code.
A: Java's HttpClient provides cookie handling through the HttpClient.Builder.cookieHandler() method. When you convert curl commands that include cookie handling (using -b
or --cookie
), our tool generates Java code that properly manages cookies.
A: While curl is excellent for quick command-line API testing, Java HttpClient provides a programmatic approach that integrates with your Java applications. Converting curl to Java helps bridge the gap between testing and implementation in Java development.
Understanding curl commands is essential for effective API testing with Java. Here's a quick reference of common curl options that our converter supports:
curl [options] [URL]
-X, --request METHOD
: Specify request method (GET, POST, PUT, DELETE, etc.)-H, --header LINE
: Add header to the request-d, --data DATA
: Send data in POST request-F, --form CONTENT
: Submit form data-u, --user USER:PASSWORD
: Server user and password-k, --insecure
: Allow insecure server connections-I, --head
: Show document info only-v, --verbose
: Make the operation more verbose-s, --silent
: Silent mode--connect-timeout SECONDS
: Maximum time for connectionOur Java converter handles complex curl commands including multiple headers, authentication, data payloads, and various options. Simply paste your curl command and get clean, modern Java code using the HttpClient library.
When working with the Java HttpClient library, follow these best practices for efficient and secure API interactions:
import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; public class HttpClientReuseExample { // Create a single HttpClient instance for the application private static final HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .build(); public static void main(String[] args) throws Exception { // First request HttpRequest request1 = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/users")) .GET() .build(); HttpResponseresponse1 = httpClient.send(request1, HttpResponse.BodyHandlers.ofString()); // Second request (uses same client) HttpRequest request2 = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/products")) .GET() .build(); HttpResponse response2 = httpClient.send(request2, HttpResponse.BodyHandlers.ofString()); } }
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpTimeoutException; public class ErrorHandlingBestPractice { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET() .build(); try { HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); switch (response.statusCode()) { case 200: case 201: System.out.println("Success: " + response.body()); break; case 400: System.out.println("Bad request: " + response.body()); break; case 401: case 403: System.out.println("Authentication error: " + response.statusCode()); break; case 404: System.out.println("Resource not found"); break; case 500: case 503: System.out.println("Server error: " + response.statusCode()); break; default: System.out.println("Unexpected status: " + response.statusCode()); } } catch (HttpTimeoutException e) { System.out.println("Request timed out: " + e.getMessage()); } catch (IOException e) { System.out.println("Network error: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("Request interrupted"); Thread.currentThread().interrupt(); } } }
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.concurrent.CompletableFuture; public class AsyncRequestExample { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET() .build(); CompletableFuture> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); futureResponse .thenApply(HttpResponse::body) .thenAccept(System.out::println) .exceptionally(e -> { System.err.println("Error: " + e.getMessage()); return null; }); // Do other work while the request is processing System.out.println("Request sent asynchronously..."); // Wait for the request to complete if needed futureResponse.join(); } }