java代碼執行curl命令


核心代碼:

public static String execCurl(String[] cmds) {
        ProcessBuilder process = new ProcessBuilder(cmds);
        Process p;
        try {
            p = process.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            return builder.toString();

        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        return null;
    }

測試用例:

public static void main(String[] args) {
        String[] cmds = {"curl", "-X", "POST",
                "http://localhost:9999/my/url?param1=1&param2=2",
                "-H", "accept: */*", "-H", "Content-Type: application/json;charset=UTF-8", "-d"
                , "{ \\\"bodyName\\\": \\\"bodyValue\\\"}"};
        System.out.println(execCurl(cmds));
    }

注意命令符需要隔開,且不能有空格。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM