有时调试 web 项目时需要使用 postman 等 api 请求工具,而有时候只需临时简单进行一些请求,此时可以无需使用 postman,杀鸡焉用牛刀。curl 是一个非常强大的命令行工具,用于在命令行或脚本中执行 HTTP 请求。它支持多种协议,但最常用的还是 HTTP 和 HTTPS。以下是一些常见的 curl 命令和参数,用于执行各种类型的 HTTP 请求。(以下内容由 ChatGPT 生成)
基本语法
1
curl [options] [URL]
常用参数
-X, --request <command>:指定请求命令,例如 GET, POST, PUT, DELETE。-d, --data <data>:发送数据,通常用于 POST 和 PUT 请求。-H, --header <header>:设置 HTTP 请求头。-i, --include:在输出中包含 HTTP 响应头。-I, --head:只请求响应头。-o, --output <file>:将输出写入指定文件。-u, --user <user:password>:设置服务器的用户和密码。-L, --location:如果服务器返回 3xx 重定向,curl会跟随重定向。-k, --insecure:允许连接到 SSL 站点时不验证证书。
GET 请求
GET 请求是最基本的请求类型,用于从服务器获取资源。
1
curl http://example.com
带自定义头的 GET 请求:
1
curl -H "Authorization: Bearer <token>" http://example.com
POST 请求
POST 请求用于向服务器提交数据。
1
curl -X POST http://example.com -d "name=John&age=30"
发送 JSON 数据的 POST 请求:
1
curl -X POST http://example.com -H "Content-Type: application/json" -d '{"name":"John", "age":30}'
PUT 请求
PUT 请求用于更新资源。
1
curl -X PUT http://example.com/resource/1 -d "name=John&age=31"
发送 JSON 数据的 PUT 请求:
1
curl -X PUT http://example.com/resource/1 -H "Content-Type: application/json" -d '{"name":"John", "age":31}'
DELETE 请求
DELETE 请求用于删除资源。
1
curl -X DELETE http://example.com/resource/1
带自定义头的 DELETE 请求:
1
curl -X DELETE http://example.com/resource/1 -H "Authorization: Bearer <token>"
例子汇总
- 简单的 GET 请求:
1
curl http://example.com
- GET 请求带参数:
1
curl "http://example.com?name=John&age=30" - GET 请求带自定义头:
1
curl -H "Authorization: Bearer <token>" http://example.com
- POST 请求发送表单数据:
1
curl -X POST http://example.com -d "name=John&age=30"
- POST 请求发送 JSON 数据:
1
curl -X POST http://example.com -H "Content-Type: application/json" -d '{"name":"John", "age":30}'
- PUT 请求更新资源:
1
curl -X PUT http://example.com/resource/1 -d "name=John&age=31"
- PUT 请求发送 JSON 数据:
1
curl -X PUT http://example.com/resource/1 -H "Content-Type: application/json" -d '{"name":"John", "age":31}'
- DELETE 请求删除资源:
1
curl -X DELETE http://example.com/resource/1 - 带自定义头的 DELETE 请求:
1
curl -X DELETE http://example.com/resource/1 -H "Authorization: Bearer <token>"
其他有用的选项
- 跟随重定向:
1
curl -L http://example.com - 输出响应到文件:
1
curl -o output.txt http://example.com - 显示请求和响应的详细信息:
1
curl -v http://example.com - 忽略 SSL 证书错误:
1
curl -k https://example.com
通过这些参数和选项,curl 可以满足你在命令行中进行 HTTP 请求的各种需求。