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

时间:2015-07-13 06:44:20

标签: java json curl

我尝试使用CURL命令和Runtime.getRuntime.exec()函数发送JSON字符串。

我的JSON字符串类似于:

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

我尝试使用以下函数发送此字符串:

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

执行以下行并解析输出后,我收到一条错误消息,指出JSON文档无效。当我使用命令行尝试相同的命令时,它工作得很好。我认为问题在于JSON字符串,因为转义字符也作为JOSN数据的一部分发送,因此输出了无效的JSON数据。

我做错了什么或者是否有其他方法我必须执行命令。

1 个答案:

答案 0 :(得分:1)

尝试修改并尝试

    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);

对于服务器端,我使用了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

服务器端代码:

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


}

}

相关问题