前言
平时接口调试都是 postman 用得比较多,图形界面,操作简单,缺点就是要多开一个软件,切换窗口。于是就想着学习一下 curl 的使用,直接在终端里调试接口。记录一下常用的请求方式及相关参数。
常用的参数
GET
GET 比较简单,不需要额外的参数。
1
| curl http://localhost:8000/api/mall/users?userId=1752938209629
|
POST
- -X 指定请求方式
- -d 指定 POST 数据,默认 Content-Type 为 application/x-www-form-urlencoded
- – json 发送 json 数据,自动设置 Content-Type 为 application/json
1 2 3 4
| curl -X POST --json '{ "username": "比六", "gender": "F" }' http://localhost:8000/api/mall/users
|
PUT
PUT 请求和 POST 请求类似
1 2 3 4
| curl -X PUT --json '{ "userId": 1752938209629, "username": "比六1" }' http://localhost:8000/api/mall/users
|
DELETE
DELETE 请求和 GET 请求类似
1
| curl -X DELETE http://localhost:8000/api/mall/users?userId=1752938209629
|
文件上传
1
| curl -F "file=@/file" http://localhost:8000/api/mall/upload
|
文件下载
- -O 使用远程文件名保存文件到本地
- -o 下载文件并重命名
1 2
| curl -O http://localhost:8000/api/mall/download curl -o myfile.zip http://localhost:8000/api/mall/download
|
其他常用参数
- -v 输出详细信息
- -H 指定请求头,如
-H "Content-Type: application/json"
- -i 输出响应头信息
终端 JSON 格式化
请求之后调用 python json 进行格式化:
1
| curl http://localhost:8000/api/mall/users | python3 -m json.tool
|
如果遇到中文乱码问题,需要修改 python/tool.py 文件: /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/tool.py
将 dump_args 修改如下:
1 2 3 4 5 6
| dump_args = { 'sort_keys': options.sort_keys, 'indent': options.indent, 'ensure_ascii': False }
|