curl 接口调用工具
后端接口开发完成,你还在为等待前端而无法调试吗?
今天分享一个小工具,curl,一个命令行文件传输工具。可用于大家平常开发的接口调用测试。
它支持文件的上传和下载,支持包括HTTP、HTTPS、ftp等众多协议,还支持POST、cookies、认证等特征。
curl命令语法:
curl [options…]
① 基本用法
curl -X GET/POST
注意,此处url前后需加双引号
@RestController @Slf4j public class CurlController { @GetMapping(“test-get”) public ResultInfo testGet(String name, String age) { log.info(“get params : name {}, age {}”, name, age); return ResultInfo.success(); } }
请求调用如下:
curl -X GET “http://localhost:12000/server/test-get?name=name1&age=12“
POST:
@PostMapping(“test-post”) public ResultInfo testPost(String name, String age) { log.info(“get params : name {}, age {}”, name, age); return ResultInfo.success(“test post response”); }
请求调用:
curl -X POST “http://localhost:12000/server/test-post?name=name1&age=12“
②请求体携带参数
-d 或者 —datacurl -X GET/POST -d “{}”
注意,此处数据前后需要加双引号
@PostMapping(“test-post-with-data”) @ResponseBody public ResultInfo testPostWithData(@RequestBody User user) { log.info(“get user {}”, user); return ResultInfo.success(user); }
请求路径:
curl -X POST “http://localhost:12000/server/test-post-with-data"-H “Content-Type: application/json” -d “{“name”:”postName”, “age”:23}”
③携带请求头信息
-H 或者 —header ,其后可以添加请求头信息,比如 Content-Type、session 等curl -X GET/POST -H “”
例如:
curl -X POST “http://localhost:12000/server/test-post-with-data“ -H “Content-Type: application/json”curl -X POST “http://localhost:12000/server/test-post-with-data“ -H “session: XXXXXXXXXXXX”
④携带cookie
-b 或者 —cookie 添加cookie到请求头curl -X POST —cookie “SESSION=XXXXXXXXXXXXXXX”
⑤下载文件
-o 或者 —output 下载文件到本地filecurl -X POST “http://localhost:12000/server/test-download“ -o “D:/home/test.xls”
@PostMapping(“download”) public void download(HttpServletResponse response) throws IOException { Workbook workbook = new HSSFWorkbook(); Sheet sheet= workbook.createSheet(); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue(“test excel”); workbook.write(response.getOutputStream()); }
调用:
curl -X POST “http://localhost:12000/server/download“ -o “D:/home/test.xls”
⑥上传文件
-F 或者 —form
上传文件到服务器,服务器端需要用name来接收curl -X POST “http://localhost:12000/server/test-upload“ -F “file=@D:/home/test.xls”
注意,此处可通过指定filename指定服务器端接收的文件名:
file=@D:/home/test.xls;filename=myexcel.xls 将本地D:/home/test.xls文件上传到服务器,服务器用file变量接收,file的getOriginalFilename()获取的文件名为myexcel.xls
@PostMapping(“upload”) public ResultInfo upload(MultipartFile testFile) throws IOException { Workbook workbook = new HSSFWorkbook(testFile.getInputStream()); Cell cell = workbook.getSheetAt(0).getRow(0).getCell(0); return ResultInfo.success(“get fileName: “ +testFile.getOriginalFilename() + “, first cell is << “ + cell.getStringCellValue() + “>>”); }
请求:
curl -X POST “http://localhost:12000/server/upload“ -F “testFile=@D:/home/test.xls;filename=ttt.xlsx”
以上基本能满足基础使用,更多使用命令可参考:
curl —help
还没有评论,来说两句吧...