我正在尝试通过我的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/