核心代码:
1public static String execCurl(String[] cmds) { 2 ProcessBuilder process = new ProcessBuilder(cmds); 3 Process p; 4 try { 5 p = process.start(); 6 BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); 7 StringBuilder builder = new StringBuilder(); 8 String line; 9 while ((line = reader.readLine()) != null) { 10 builder.append(line); 11 builder.append(System.getProperty("line.separator")); 12 } 13 return builder.toString(); 14 15 } catch (IOException e) { 16 System.out.print("error"); 17 e.printStackTrace(); 18 } 19 return null; 20 }
测试用例:
1public static void main(String[] args) { 2 String[] cmds = {"curl", "-X", "POST", 3 "http://localhost:9999/my/url?param1=1¶m2=2", 4 "-H", "accept: */*", "-H", "Content-Type: application/json;charset=UTF-8", "-d" 5 , "{ \\\"bodyName\\\": \\\"bodyValue\\\"}"}; 6 System.out.println(execCurl(cmds)); 7 }
注意命令符需要隔开,且不能有空格。