简体   繁体   中英

Unable to send JSON string through java Runtime.getRuntime.exec();

I'm trying to send a JSON string using CURL command and Runtime.getRuntime.exec() function.

My JSON string is something like:

String jsonString = "{\"object\":[\"something\",\"another something\"]}"

I'm trying to send this string using the following function:

Process p;
p = Runtime.getRuntime().exec(new String[] {"curl","someURL","-H","Content-Type:application/json","-d",jsonString,"-u","something:something"}

Once I execute the following lines and parse the output, I get an error saying that the JSON document is not valid. When I try the same command using command line, it works just fine. I think the problem is with the JSON string as the escape characters are also being send as a part of the JOSN data and hence the invalid JSON data output.

Is there anything that I have done wrong or is there any other way that I have to execute the command.

Just tried like with a modification and worked

    String jsonString = "{\"object\":[\"something\",\"another something\"]}";

    ProcessBuilder ps = new ProcessBuilder(new String[] { "curl", "http://localhost:8338", "-H",
            "Content-Type:application/json", "-d", jsonString, "-u", "something:something" });
    ps.redirectErrorStream(true);
    Process pr = ps.start();  

    BufferedReader in = new BufferedReader(new 

    InputStreamReader(pr.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    pr.waitFor();

    in.close();
    System.exit(0);

For server side I used Pippo webframework and it returned me an OK string

     % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed

    0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:-     -:--     0
    100    46    0     2  100    44    329   7247 --:--:-- --:--:-- --:--:--  7333
    OK

Server side code:

public class PippoApplication extends Application {

private final static Logger log = LoggerFactory.getLogger(PippoApplication.class);

@Override
protected void onInit() {


    POST("/", new RouteHandler() {

        @Override
        public void handle(RouteContext routeContext) {
            System.out.println(routeContext.getRequest().getBody());
            routeContext.send("OK");
        }
    });


}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM