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

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

猜你喜欢

转载自www.cnblogs.com/miaoying/p/12426857.html
今日推荐