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¶m2=2",
"-H", "accept: */*", "-H", "Content-Type: application/json;charset=UTF-8", "-d"
, "{ \\\"bodyName\\\": \\\"bodyValue\\\"}"};
System.out.println(execCurl(cmds));
}
注意命令符需要隔开,且不能有空格。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册⭐️ Admin快速开发: https://show.cool-admin.com/
赞 0⭐️ 官方文档: https://cool-js.com
赞 0⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld
赞 0