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

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

通过删除网址周围的引号来更改 String 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();
}

最佳答案

对我来说,这看起来像是引号问题。 尽量保持一致,尽量用反斜杠转义下面的引号

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

PS:我刚刚将网址引号从“更改为'

关于java - 在java应用程序中执行curl命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37573063/

相关文章:

javascript - 在等待 curl_exec 获取响应时显示 Gif

java - 如何通过Java在Linux中执行decode -t 17?

java - Spring Boot——嵌入式Tomcat

javascript - 在js中将json解析为.csv

java - 转换结果时出错 java.lang.NullPointerException : lock == null, 为什么会出现此错误?

javascript - NodeJS 不响应 CURL 请求

java - Spring native 应用程序构建失败并出现构建回溯

java - 在 Spring 中与 Hibernate 并发

json - 如何将 JSON 反序列化为 F# 中记录的映射/字典?

ruby-on-rails - 尝试安装 RoR 时安装 RVM 失败