Skip to content

cURL Command Builder — Java source

Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.

This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// curl-builder — structured input → copy-paste curl command + reverse parser.
// Java port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
// Java 8+, standard library only. Composes a copy-paste curl command from
// structured input; also parses an existing command back into the structure
// (round-trip). Values are single-quoted with embedded quotes escaped
// (' → '\'') — safe for POSIX shells. The flag order is fixed and
// deterministic: method (-X) → headers (-H, insertion order) → auth (-u) →
// data (-d) → boolean flags (-I -k -L --compressed) → the URL last. Absent
// optional fields are null; null data is treated like "" (omitted). Never
// throws — errors travel in the result's nullable error field (null on
// success). Package-private: display snippets keep the repo filename
// (java.java), which need not match the class name.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

final class CurlBuilder {

    static final class Header {
        final String key, value;
        Header(String key, String value) { this.key = key; this.value = value; }
    }

    static final class Auth {
        final String user, password;
        Auth(String user, String password) { this.user = user; this.password = password; }
    }

    static final class CurlRequest {
        String url = "";
        String method;                                    // null = GET
        final List<Header> headers = new ArrayList<>();   // insertion order kept
        String data;                                      // null or "" → omitted
        Auth auth;                                        // null = absent
        boolean headOnly, insecure, followRedirects, compressed;
    }

    static final class BuildResult {
        final String command;
        final String error;
        BuildResult(String command, String error) { this.command = command; this.error = error; }
    }

    static final class ParsedCurl {
        final CurlRequest request;
        final List<String> unknownFlags;
        ParsedCurl(CurlRequest request, List<String> unknownFlags) {
            this.request = request;
            this.unknownFlags = unknownFlags;
        }
    }

    static final class ParseResult {
        final ParsedCurl parsed;
        final String error;
        ParseResult(ParsedCurl parsed, String error) { this.parsed = parsed; this.error = error; }
    }

    private static final String[] METHODS = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"};

    /** POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
    static String shellQuote(String value) {
        return "'" + value.replace("'", "'\\''") + "'";
    }

    private static boolean isHeaderKey(String k) {
        if (k == null || k.isEmpty()) return false;
        for (int i = 0; i < k.length(); i++) {
            char c = k.charAt(i);
            if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false;
        }
        return true;
    }

    /** Build the curl command. URL required; method/header names validated. */
    static BuildResult buildCurlCommand(CurlRequest req) {
        String url = req.url == null ? "" : req.url.trim();
        if (url.isEmpty()) return new BuildResult("", "A URL is required");
        if (!(url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") || url.startsWith("$")))
            return new BuildResult("", "URL must start with http://, https://, / or $ (a variable)");
        String rawMethod = req.method == null ? "GET" : req.method;
        String method = rawMethod.toUpperCase(Locale.ROOT);
        boolean known = false;
        for (String m : METHODS) if (m.equals(method)) known = true;
        if (!known)
            return new BuildResult("", "unsupported method " + req.method + " (use " + String.join(", ", METHODS) + ")");
        for (Header h : req.headers)
            if (!isHeaderKey(h.key))
                return new BuildResult("", "invalid header name \"" + h.key + "\" (letters, digits and hyphens only)");
        List<String> parts = new ArrayList<>();
        parts.add("curl");
        if (!method.equals("GET")) parts.add("-X " + method);
        for (Header h : req.headers) parts.add("-H " + shellQuote(h.key + ": " + h.value));
        if (req.auth != null) parts.add("-u " + shellQuote(req.auth.user + ":" + req.auth.password));
        if (req.data != null && !req.data.isEmpty()) parts.add("-d " + shellQuote(req.data));
        if (req.headOnly) parts.add("-I");
        if (req.insecure) parts.add("-k");
        if (req.followRedirects) parts.add("-L");
        if (req.compressed) parts.add("--compressed");
        parts.add(shellQuote(url));
        return new BuildResult(String.join(" ", parts), null);
    }

    /** Shell word-split respecting single and double quotes. */
    private static List<String> splitWords(String line) {
        List<String> words = new ArrayList<>();
        StringBuilder cur = new StringBuilder();
        Character quote = null;
        boolean has = false;
        for (int i = 0; i < line.length(); i++) {
            char ch = line.charAt(i);
            if (quote != null) {
                if (ch == quote) quote = null;
                else cur.append(ch);
            } else if (ch == '\'' || ch == '"') {
                quote = ch;
                has = true;
            } else if (ch == ' ' || ch == '\t') {
                if (cur.length() > 0 || has) words.add(cur.toString());
                cur.setLength(0);
                has = false;
            } else {
                cur.append(ch);
                has = true;
            }
        }
        if (has) words.add(cur.toString()); // any accumulated characters imply has
        return words;
    }

    /** Parse a curl command line back into a request (best effort, ordered). */
    static ParseResult parseCurlCommand(String line) {
        String trimmed = line == null ? "" : line.trim();
        if (trimmed.isEmpty()) return new ParseResult(null, "A command is required");
        List<String> words = splitWords(trimmed.replace("\\\n", " "));
        if (words.isEmpty() || !words.get(0).equals("curl"))
            return new ParseResult(null, "command must start with curl");
        CurlRequest req = new CurlRequest();
        List<String> unknown = new ArrayList<>();
        int n = words.size();
        for (int i = 1; i < n; i++) {
            String w = words.get(i);
            if (w.equals("-X") || w.equals("--request")) {
                if (i + 1 < n) req.method = words.get(++i);
            } else if (w.equals("-H") || w.equals("--header")) {
                if (i + 1 < n) {
                    String raw = words.get(++i);
                    int at = raw.indexOf(':');
                    if (at > 0) req.headers.add(new Header(raw.substring(0, at).trim(), raw.substring(at + 1).trim()));
                }
            } else if (w.equals("-u") || w.equals("--user")) {
                if (i + 1 < n) {
                    String raw = words.get(++i);
                    int at = raw.indexOf(':');
                    req.auth = at < 0 ? new Auth(raw, "") : new Auth(raw.substring(0, at), raw.substring(at + 1));
                }
            } else if (w.equals("-d") || w.equals("--data")) {
                if (i + 1 < n) req.data = words.get(++i);
            } else if (w.equals("-I") || w.equals("--head")) req.headOnly = true;
            else if (w.equals("-k") || w.equals("--insecure")) req.insecure = true;
            else if (w.equals("-L") || w.equals("--location")) req.followRedirects = true;
            else if (w.equals("--compressed")) req.compressed = true;
            else if (w.startsWith("-")) unknown.add(w);
            else req.url = w;
        }
        if (req.url.isEmpty()) return new ParseResult(null, "no URL found in command");
        return new ParseResult(new ParsedCurl(req, unknown), null);
    }
}

// Example:
// CurlBuilder.shellQuote("it's") → "'it'\\''s'"
// CurlBuilder.CurlRequest req = new CurlBuilder.CurlRequest();
// req.url = "https://api.example.com"; req.method = "post";
// req.headers.add(new CurlBuilder.Header("X-Tag", "it's")); req.data = "k=v";
// CurlBuilder.buildCurlCommand(req).command
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →