简体   繁体   English

无法通过java Runtime.getRuntime.exec()发送JSON字符串;

[英]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. 我正在尝试使用CURL命令和Runtime.getRuntime.exec()函数发送JSON字符串。

My JSON string is something like: 我的JSON字符串类似于:

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. 一旦执行以下行并解析了输出,就会收到一条错误消息,指出JSON文档无效。 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. 我认为问题在于JSON字符串,因为转义字符也作为JOSN数据的一部分发送,因此无效的JSON数据输出也已发送。

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 对于服务器端,我使用了Pippo webframework,它返回了一个OK字符串

     % 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");
        }
    });


}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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