Linux基础 -- 网络工具之curl使用

curl 使用手册

curl 是一个强大的命令行工具,用于与服务器进行HTTP请求。本文档将介绍常见的请求方法和一些高级用法。

基础用法

1. GET 请求

GET 请求用于从服务器获取数据。

curl -X GET "http://example.com/api/resource"

2. POST 请求

POST 请求用于向服务器发送数据,通常用于创建新资源。

curl -X POST "http://example.com/api/resource" \
-H "Content-Type: application/json" \
-d '{"name": "example", "value": "123"}'

3. PUT 请求

PUT 请求通常用于更新服务器上的资源。

curl -X PUT "http://example.com/api/resource/1" \
-H "Content-Type: application/json" \
-d '{"name": "updated_example", "value": "456"}'

4. DELETE 请求

DELETE 请求用于删除服务器上的资源。

curl -X DELETE "http://example.com/api/resource/1"

高级用法

1. 发送表单数据

可以通过curl发送表单数据,通常用于模拟HTML表单提交。

curl -X POST "http://example.com/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=myuser&password=mypass"

2. 处理文件上传

curl 可以用来上传文件。

curl -X POST "http://example.com/upload" \
-F "file=@/path/to/file.jpg" \
-F "name=myfile"

3. 设置多个 Header

可以在请求中设置多个 Header。

curl -X GET "http://example.com/api/resource" \
-H "Authorization: Bearer your_token" \
-H "Accept: application/json"

4. 使用 Cookie

curl 可以管理 Cookie,发送带有 Cookie 的请求,或保存和加载 Cookie。

# 保存 Cookie 到文件
curl -c cookies.txt -X GET "http://example.com/login"

# 使用 Cookie 文件发送请求
curl -b cookies.txt -X GET "http://example.com/dashboard"

5. 使用代理

curl 可以通过代理服务器发送请求。

curl -X GET "http://example.com/api/resource" \
--proxy http://proxy.example.com:8080

6. 处理重定向

默认情况下,curl 不会自动跟随重定向,但可以通过添加选项使其自动跟随。

curl -L "http://example.com/redirect"

7. 限制请求速率

curl 可以限制上传和下载速度,模拟低带宽环境。

curl -X GET "http://example.com/api/resource" \
--limit-rate 100k

8. 处理响应数据

curl 可以通过 -o-O 选项保存响应数据到文件。

# 将响应数据保存到指定文件
curl -X GET "http://example.com/api/resource" -o output.txt

# 使用响应数据中的文件名保存
curl -X GET "http://example.com/api/resource" -O

9. 设置超时时间

可以设置 curl 请求的连接超时和总超时时间。

curl -X GET "http://example.com/api/resource" \
--connect-timeout 10 \
--max-time 30

10. 调试和查看详细输出

curl 提供了详细的调试输出选项,帮助排查问题。

curl -X GET "http://example.com/api/resource" \
-v

11. 发送自定义请求

可以发送自定义的HTTP请求方法,例如PATCH。

curl -X PATCH "http://example.com/api/resource/1" \
-H "Content-Type: application/json" \
-d '{"field": "new_value"}'

12. 组合多个选项

可以组合多个 curl 选项,以满足复杂需求。

curl -X POST "http://example.com/api/upload" \
-F "file1=@/path/to/file1.jpg" \
-F "file2=@/path/to/file2.png" \
-H "Authorization: Bearer your_token" \
--limit-rate 500k \
-v
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值