Execute terminal command in java with httpurlconnection and get response in json format

独自空忆成欢 提交于 2019-12-11 03:46:36

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/28291337/execute-terminal-command-in-java-with-httpurlconnection-and-get-response-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!