我有一个在端口4000上运行的localhost服务器,它监听发送给它的请求并执行命令并以json格式将输出返回给客户端。
我正在尝试从tomcat的端口8080向它发送请求,我需要它来执行命令并以json格式发回输出。
我能够通过php使用curl和执行的命令来完成它,但我需要java中的解决方案,所以我做了以下代码:
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();
}
我收到了响应"OK"
和端口4000的默认输出。但是命令没有执行。
知道我缺少什么吗?或者做错了?
根据热门需求编辑:php curl功能
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
这里是http://localhost:4000
和$command
只是传递了任何命令。
答案 0 :(得分:1)
您的OutputStream无法调用任何终端命令,因为它仅绑定到您的http连接。要从jvm运行终端命令,您可以使用Runtime.getRuntime().exec
作为替代方案,您可以使用我喜欢的Apache Commons Exec。
最简单的方法是在函数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 + "\n");
}
// your output that you can use to build your json response:
output.toString();