在java中使用httpurlconnection执行终端命令,并以json格式获取响应 [英] Execute terminal command in java with httpurlconnection and get response in json format
问题描述
我有一个在4000端口上运行的本地服务器,监听发送到它的请求,并执行命令并以json格式将输出返回给客户端。
我试图从tomcat的端口8080发送一个请求到它,我需要它执行一个命令,并以json格式发送输出。
我能够通过php使用curl和执行的命令,但我需要解决方案在java中,所以我做了以下代码:
public String sendData()throws IOException {
// curl_init和url
URL url = new URL(http:// localhost: 4000);
HttpURLConnection con =(HttpURLConnection)url.openConnection();
// CURLOPT_POST
con.setRequestMethod(POST);
// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);
String postData =ls; //只是尝试一个简单的命令
con.setRequestProperty(Content-length,String.valueOf(postData.length()));
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();
//发送数据发送...等待回复);
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println(Response(Code):+ code);
System.out.println(Response(Message):+ con.getResponseMessage());
//读取响应
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while((c = input.read())!= -1){
resultBuf.append((char)c);
}
input.close();
return resultBuf.toString();
}
我收到一个回应 OK
和端口4000的默认输出。但该命令不执行。
任何想法我错过了什么?或者做错了?
根据热门需求编辑:php curl函数
protected function HTTPRequest($ url,$ command){
//打开连接
$ ch = curl_init
$ fields ['command'] = $ command;
//设置url,POST变量的数量,POST数据
curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_POST,1);
curl_setopt($ ch,CURLOPT_POSTFIELDS,http_build_query($ fields));
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);
//执行post
$ result = curl_exec($ ch);
//关闭连接
curl_close($ ch);
return $ result;
}
$ url
这里是 http:// localhost:4000
和 $ command
命令。
您的OutputStream不能调用任何终端命令,因为它仅绑定到您的http连接。要从jvm运行终端命令,可以使用 Runtime.getRuntime()。exec
另一种方法是使用Apache Commons Exec。 / p>
最简单的方法是在函数sendData()中调用命令。像这样:
StringBuffer output = new StringBuffer();
Process p = Runtime.getRuntime()。exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line =;
while((line = reader.readLine())!= null){
output.append(line +\\\
);
}
//你的输出,你可以用来构建你的json响应:
output.toString();
I have a localhost server running on port 4000 which listens to requests sent to it and executes commands and returns output to client in a json format.
I'm trying to send a request from tomcat's port 8080 to it and i need it to execute a command and send output back in json format.
I was able to do it through php using curl and the command executed but I need the solution in java so I made the following code:
public String sendData() throws IOException {
// curl_init and url
URL url = new URL("http://localhost:4000");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// CURLOPT_POST
con.setRequestMethod("POST");
// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);
String postData = "ls"; //just trying a simple command
con.setRequestProperty("Content-length", String.valueOf(postData.length()));
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();
// "Post data send ... waiting for reply");
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());
// read the response
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ( (c = input.read()) != -1) {
resultBuf.append((char) c);
}
input.close();
return resultBuf.toString();
}
I'm getting a response "OK"
and the default output of the port 4000. But the command doesn't execute.
Any idea what I'm missing? Or doing wrong?
Edit on popular demand: The php curl function
protected function HTTPRequest($url, $command){
//open connection
$ch = curl_init();
$fields['command'] = $command;
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
$url
here is http://localhost:4000
and $command
is just any command is passed.
Your OutputStream cannot call any terminal command, because it's bound to your http connection only. To run terminal commands from the jvm, you can use Runtime.getRuntime().exec
As an alternative you can use Apache Commons Exec, which I prefer.
Easiest way for you is to call your command in your function sendData(). Do it like this:
StringBuffer output = new StringBuffer();
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
// your output that you can use to build your json response:
output.toString();
这篇关于在java中使用httpurlconnection执行终端命令,并以json格式获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!