【问题标题】:Execute terminal command in java with httpurlconnection and get response in json format使用httpurlconnection在java中执行终端命令并以json格式获取响应
【发布时间】:2015-02-03 04:22:56
【问题描述】:

我有一个 localhost 服务器在端口 4000 上运行,它监听发送给它的请求并执行命令并以 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 只是通过任何命令。

【问题讨论】:

  • 您是否检查了在端口 4000 上运行的应用程序?那收到请求了吗?是否能够成功读取命令?
  • 请向我们展示有效的curl 命令。并告诉您的 servlet 中发生了什么。我觉得奇怪的是使用DataOutputStream。尝试不使用它,只需简单的 con.getOutputStream。
  • @ramp,使用 php curl 命令可以。但是对于上面的java,没有。它只响应服务器的默认响应。
  • @hgoebl 当然,我会编辑这个问题。我也会试试你的建议。
  • @hgoebl con.getOuputStream 没有输出。

标签: java json jsp curl httpurlconnection


【解决方案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();

【讨论】:

  • 好的,我要在同一个函数中添加它吗?还是别的地方?
  • 我也想过这个,但是不知道在哪里实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 2015-01-27
  • 2014-12-15
  • 1970-01-01
  • 2015-08-16
  • 2016-10-09
相关资源
最近更新 更多