9

I want to know the command that will be executed before it happens.

      String cmd[] = {"curl",
            "-X",
            "POST",
            "https://api.renam.cl/medicion/insert?access-token={Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD}",
            "-H",
            "content-type: application/json",
            "-d",
            json.toString()};

        ProcessBuilder pb = new ProcessBuilder(cmd);

        Log.debug("COMANDO.TOSTRING " + pb.command().toString());

        Process p = pb.start();

        Log.debug(p.getOutputStream().toString());

        p.waitFor();

        BufferedReader reader
                = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String readline;

        while ((readline = reader.readLine()) != null) {
            Log.debug(readline);
        }

With the readline I have the server answer output but I don't know hot to get the curl command I have exectuted with the processbuilder.

EDIT 1:

I just need to send this command by using the linux console:

curl -X POST 'https://api.com/data/insert?access-token=Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD' -H 'content-type: application/json' -d '{ "pm25":2, "timestamp":1495077872, "dispositivo_mac": "12:34:56:78:90:12" }'

Basically I need to print the cmd array processed by the ProcessBuilder object to see it before the star method execution.

2 Answers2

2

I had success with this code:

ProcessBuilder pb = new ProcessBuilder(command);    
logger.debug(String.join(" ",pb.command().toArray(new String[0])));
A.Sol
  • 41
  • 5
-3

Here is code for printing the runnable command:

private String getRunnableCommand(ProcessBuilder processBuilder)
{
    List<String> commandsList = processBuilder.command();
    StringBuilder runnableCommandBuilder = new StringBuilder();
    int commandIndex = 0;
    for (String command : commandsList)
    {
        if (command.contains(" "))
        {
            runnableCommandBuilder.append("\"");
        }
        runnableCommandBuilder.append(command);

        if (command.contains(" "))
        {
            runnableCommandBuilder.append("\"");
        }

        if (commandIndex != commandsList.size() - 1)
        {
            runnableCommandBuilder.append(" ");
        }

        commandIndex++;
    }
    return runnableCommandBuilder.toString();
}

It will surround arguments containing spaces properly with quotation marks.

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185