在java应用程序中执行curl命令

时间:2016-06-01 15:33:45

标签: java json curl

我正在尝试通过我的java应用程序执行curl命令(在终端中工作)。我尝试过使用流程构建器和Runtime.exec()。我能够连接,但响应要么

{"result":0,"reason":"Unknown Json request format"} 

{"result":0,"reason":"Invalid client request Json string"}.

这是在终端中工作的curl命令:

curl -X POST -d '{"command":"get","user":"R16","id":5552}' "http://<Ex.webaddress>"

运行时,连接失败

String testCurlCommand = "curl -X POST -d '{\"command\":\"get\",\"user\":\"R16\",\"id\":5552}' \"http://<Ex.webaddress\"";try {
        //final Process terminal = curlCommand.start();
        Process p = Runtime.getRuntime().exec(testCurlCommand);
        try {
            String responseString = readInputStream(p.getInputStream());
            JSONObject job = new JSONObject(responseString);

            // job.getString("Parameter")
            statusLabel.setText("Command Result: " + job.toString());
            connectionStatusLabel.setText("Connection Status: Successful");
        } catch (JSONException e) {
            statusLabel.setText("Command Result: 0");
            connectionStatusLabel.setText("Connection Status: Failed");
        }
    } catch (IOException ex) {
        statusLabel.setText("Command Result: 0");
        connectionStatusLabel.setText("Connection Status: Failed");
    }

当通过删除网址周围的引号来更改字符串testCurlCommand时,连接有效,但我得到“未知的Json请求格式”

String testCurlCommand = "curl -X POST -d '{\"command\":\"get\",\"user\":\"R16\",\"id\":5552}' http://<Ex.webaddress";

我试过删除转义的引号,我仍然得到相同的。我也尝试过使用流程构建器:

ProcessBuilder testCurlCommand = new ProcessBuilder("curl", "-X", "POST", "-d", "'{\"command\":\"get\",\"user\":\"R16\",\"id\":\"5552\"}'", "\"http://<examplewebaddress>\"")

我认为它与格式化(额外的引用或某事)有关,但我不确定。非常感谢任何帮助。我将在下面添加readInputStream函数:

static private String readInputStream(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            inputStream, "UTF-8"));
    String tmp;
    StringBuilder sb = new StringBuilder();
    while ((tmp = reader.readLine()) != null) {
        sb.append(tmp).append("\n");
    }
    if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
        sb.setLength(sb.length() - 1);
    }
    reader.close();
    return sb.toString();
}

2 个答案:

答案 0 :(得分:1)

对我来说,这看起来像一个引号问题。 尝试保持一致,并尝试使用反斜杠

来转义以下引号
curl -X POST -d '{"command":"get","user":"R16","id":5552}' 'http://<Ex.webaddress>'

PS:我刚刚更改了&#34;的网址引号到&#39;

答案 1 :(得分:1)

我知道的最好方法是使用DavidWebb

你可以这样做:

Response<JSONObject> result = Webb.create().post("http://<Ex.webaddress>")
        .body("{\"command\":\"get\",\"user\":\"R16\",\"id\":5552}").asJsonObject();
JSONObject job = result.getBody();