curl命令及用法

curl(Client URL)是一个命令行工具,用于向服务器发送请求并获取数据。它支持多种协议,包括HTTP、HTTPS、FTP等,广泛应用于Web开发和调试网络应用。以下是一些常用的curl命令及其用法示例:

基本语法

1. 发送GET请求
默认情况下,curl发送GET请求。

curl http://example.com

2. 发送POST请求
使用-X POST或者–data选项。

curl -X POST http://example.com -d "param1=value1&param2=value2"
或者

curl http://example.com --data "param1=value1&param2=value2"

3. 发送JSON数据的POST请求
使用-H指定Content-Type为application/json。

curl -X POST http://example.com -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}'

4. 添加请求头
使用-H选项。

curl -H "Authorization: Bearer <token>" http://example.com

5. 发送表单数据
使用–form选项。

curl -X POST http://example.com --form "field1=value1" --form "field2=@file.txt"

 

6. 保存响应内容到文件
使用-o选项。

curl http://example.com -o output.txt
1
7. 查看响应头
使用-I选项。

curl -I http://example.com
1
8. 跟踪重定向
使用-L选项。

curl -L http://example.com
1
9. 指定请求方法
使用-X选项。

curl -X DELETE http://example.com/resource/1
1
10. 设置请求超时时间
使用–max-time选项。

curl --max-time 10 http://example.com
1
11. 显示详细请求和响应信息
使用-v选项。

curl -v http://example.com
1
12. 通过代理发送请求
使用-x选项。

curl -x http://proxyserver:port http://example.com
1
13. 上传文件
使用-T选项。

curl -T file.txt ftp://example.com/ --user username:password

curl -X POST http://example.com/api/resource \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{"name":"example", "value":"123"}' \
-o response.json \
--max-time 10 \
-v

 

以上命令发送一个带有JSON数据的POST请求,附带认证头,将响应保存到response.json文件中,并设置请求超时时间为10秒,同时显示详细信息。

常见用法总结
GET请求:curl http://example.com
POST请求:curl -X POST http://example.com -d “param=value”
发送JSON数据:curl -X POST http://example.com -H “Content-Type: application/json” -d ‘{“key”:“value”}’
保存响应:curl http://example.com -o output.txt
查看响应头:curl -I http://example.com
跟踪重定向:curl -L http://example.com
curl是一个强大的工具,适用于各种HTTP请求和数据传输需求,掌握其用法能显著提高网络调试和开发的效率。
————————————————

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/weixin_48255612/article/details/139168223

posted @ 2024-07-30 16:27  吕金林  阅读(184)  评论(0编辑  收藏  举报