Search code examples
javacurlprocessbuilderbearer-token

Executing curl command with ProcessBuilder and bearer token


I am trying to execute a curl PUT request which contains a bearer token for the authorization header, using ProcessBuilder. There is some issue with how ProcessBuilder is parsing the quotes for the header and I can't figure out how to write the curl command. This is the command:

curl -H "Authorization: Bearer <token>" -T kubernetes.hpi -X PUT "https://<url>"

I've seen some solutions where not putting quotes was helpful, but in this case the header contains spaces so that doesn't work for me. For the header, I've tried single quotes, escaping double quotes, no quotes, etc.

I either get a 401 error

{
  "errors" : [ {
    "status" : 401,
    "message" : "Unauthorized"
} ]

or I get errors from curl

curl: (3) URL using bad/illegal format or missing URL

How can I write the command so that it works with ProcessBuilder? The command works in the command line, but I get errors from curl with ProcessBuilder.

String deployPath =
    String.format(
        "%s%s/%s_%s/%s.hpi;ID=%s",
        artifactoryLocalRepoUrl,
        pluginName,
        jenkinsPluginDetail.getPluginVersion(),
        currUTCMillis,
        pluginName,
        jenkinsPluginDetail.getId().toString());
String[] deployArtifactCmd =
        new String[] {
          "curl",
          "-T",
          outputPath,
                "-X",
                "PUT",
                deployPath,
                "-H",
                "\'Authorization: Bearer " + bearerToken + "\'"
        };
    
    logger.info(" Executing deploying plugin {}", pluginName);
    ProcessBuilder processBuilder2 =
        new ProcessBuilder().inheritIO().command(deployArtifactCmd).redirectErrorStream(true);
    logger.info(processBuilder2.command().toString());
    try {
       Process process = processBuilder2.start();
       ...

Solution

  • The parameters passed to ProcessBuilder should not need quote characters. Your shell would strip them when passing on the command line to curl. Your last parameter has quotes so try without the quotes:

    "Authorization: Bearer " + bearerToken
    

    The quotes are needed in shell so that it recognises spaces as continuation of a parameter value. They are unnecessary in Java as you can supply a value with spaces in the array of arguments.