HOWTO · Java

How to Use cURL in Java

This tutorial educates about cURL and demonstrates its uses via code examples in Java.

On this page

Today, you can invoke the external cURL command-line program from Java when a task or existing workflow specifically depends on it. ProcessBuilder is usually the clearer choice because each command argument is a separate value. Runtime.getRuntime() also starts a process, but its string overload is easy to misuse. The example below starts a local HTTP service itself, so it does not depend on an external server.

What cURL does in a Java application

cURL transfers data using protocols such as HTTP. It is a separate executable, not a Java API. Calling it from Java means starting an operating-system process, then managing that process’s input, output, error stream, and lifetime. Java’s HttpURLConnection and HTTP client libraries make requests inside the JVM instead; choose one of those when you do not need the cURL executable or its options.

Prepare cURL and Java

Install cURL and make its executable discoverable through the environment inherited by the Java process, or provide its absolute executable path. Setting a process working directory only changes where that process runs; it does not locate cURL. The examples use curl, which assumes the executable is on PATH. Replace it with a platform-appropriate path when needed. The Java code requires a JDK with the jdk.httpserver module, which is included in standard JDK distributions.

Run cURL with ProcessBuilder

Pass the executable and every option as separate arguments. Do not build one command string and split it on spaces: a URL, header, or form value can itself contain spaces or shell-significant characters. Encode query parameter values as URLs require, and keep each --data value in one argument. ProcessBuilder starts the program directly; it does not invoke a shell to expand operators such as &.

Run this example:

import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class CurlGet {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/get", exchange -> {
            byte[] body = "Local response\n".getBytes(StandardCharsets.UTF_8);
            exchange.sendResponseHeaders(200, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.start();
        try {
            String url = "http://127.0.0.1:" + server.getAddress().getPort() + "/get";
            Process process = new ProcessBuilder(
                    "curl", "--silent", "--show-error", "--max-time", "10",
                    "--get", "--data-urlencode", "delft1=stack1",
                    "--data-urlencode", "delft2=stack2", url)
                    .redirectErrorStream(true)
                    .start();
            byte[] response;
            try (InputStream stream = process.getInputStream();
                 ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[4096];
                int count;
                while ((count = stream.read(buffer)) != -1) {
                    bytes.write(buffer, 0, count);
                }
                response = bytes.toByteArray();
            }
            int exitCode = process.waitFor();
            System.out.print(new String(response, StandardCharsets.UTF_8));
            System.out.println("cURL process exit code: " + exitCode);
        } finally {
            server.stop(0);
        }
    }
}
Local response
cURL process exit code: 0

The local server binds to an available loopback port, returns a fixed body, and shuts down after the request. The --get and --data-urlencode options create a query string while preserving each argument boundary. Merging stderr into stdout lets this example drain one stream before waiting, avoiding a pipe-buffer deadlock. In an application, keep response data separate from diagnostics if callers need to process the body. A remote service can return different content, and cURL’s exit code can differ if the request fails.

Run cURL with Runtime.getRuntime().exec()

The array overload of exec also preserves argument boundaries. For a POST form request, the argument list can be written as new String[] { "curl", "--silent", "--show-error", "--data", "delft1=stack1&delft2=stack2", "http://127.0.0.1:8080/post" }. This is a syntax illustration; the URL is illustrative and this expression is not run by the example above.

Runtime.getRuntime().exec(String) tokenizes a command string on whitespace; it does not apply shell quoting rules, so values containing spaces can become multiple arguments. Prefer the array overload or ProcessBuilder when boundaries matter. Avoid adding shell quoting to either API unless you explicitly launch a shell and account for that shell’s platform-specific rules.

Read the response and handle the process

Read stdout and stderr while the process is running, then call waitFor() before obtaining its exit code. If both streams are piped, drain them concurrently or merge them; otherwise a full pipe can stop cURL while Java waits on the other stream. Close streams when finished. waitFor() reports the cURL process exit status, which indicates whether the command completed successfully; it is not the HTTP response status. To inspect an HTTP status, ask cURL to print it with an appropriate write-out option and parse that separate output, or use a Java HTTP client.

Set a cURL timeout for network operations and handle interruption by restoring the thread’s interrupt status and terminating the child if appropriate. Close process streams and release the process when work is complete; destroy() is for stopping a process, not a substitute for reading its output or waiting for normal completion. For long-running applications, also consider a bounded wait and destroyForcibly() fallback so a child cannot outlive the request indefinitely.