curl概述
GitHub地址:https://github.com/curl/curl
curl全称Client URL,是一个命令行工具和库,用于通过 URL 传输数据,支持 100+ 协议(HTTP/HTTPS、FTP、SMTP、POP3、RTSP、DICT 等)。
其作用主要是发送网络请求、接收响应、支持文件上传 / 下载、处理认证、代理、Cookie、重定向等复杂网络操作。
其以轻量简洁、跨平台(Linux、Windows、Mac)、脚本友好(适合自动化和 API 测试)等特点深受广大程序员的喜爱。
curl应用场景
- API 调试:测试 RESTful 接口(GET/POST/PUT/DELETE 等)。
- 文件传输:下载远程文件、上传文件到服务器(如 FTP/SCP)。
- 网络诊断:检查服务器响应状态、分析请求头 / 响应头。
- 数据采集:爬取网页内容(需注意网站 robots 协议)。
- 脚本自动化:在 Shell/Python 脚本中集成网络请求。
curl的基本使用
安装
# linux debian系列
apt install -y curl
# linux CentOS系列
yum install -y curl
curl的语法
# 其中options是选项参数,url表示请求的路径
curl [options] [url]
常用选项参数
请求控制选项
-
-X,--request:指定请求方法(GET、POST、PUT、DELETE...)
curl -X GET https://www.baidu.com
-
-H, --header:添加请求头,可以多次指定
curl -H "content-type: application/json; charset=utf-8"
-H "Authorization: Bearer TOKEN"
https://api.example.com -
-d:发送 POST 数据(表单数据,自动设置 Content-Type: application/x-www-form-urlencoded)
curl -d "name=John&age=30" https://api.example.com/submit
-
-D, --dump-header:将响应头保存到文件
curl -D headers.txt https://www.baidu.com
-
-L, --location:自动跟随重定向(301/302 状态码)
curl -L http://www.baidu.com
-
-b, --cookie:发送 Cookie(格式:name=value 或文件路径)
curl -b "sessionid=12345" https://example.com
-
-c, --cookie-jar:将服务器返回的cookie保存到本地文件,便于后续访问
curl -c cookies.txt https://example.com/login
数据传输选项
-
-o:下载内容保存到文件
curl -o download.zip https://example.com/file.zip
-
-O:下载内容,文件名称跟随远程文件
curl -O https://example.com/file.zip
-
-d:发送 POST 数据(表单数据,自动设置 Content-Type: application/x-www-form-urlencoded)
curl -d "name=John&age=30" https://api.example.com/submit
-
-F, --form:发送表单文件 / 数据(模拟浏览器上传,自动设置 multipart/form-data)
-
-T, --upload-file:上传文件(PUT 或 POST 请求)
curl -T report.pdf ftp://ftp.example.com/upload/
输出与调试选项
-
-v, --verbose 显示详细调试信息(请求头、响应头、连接过程等)
curl -v https://www.baidu.com
-
-s, --silent:静默模式(不显示进度条),但错误信息仍会显示。
curl -s https://example.com > content.txt
-
-S, --show-error 在静默模式下显示错误信息(需配合 -s)
curl -sS https://invalid-url.com
-
--trace:跟踪请求过程(更详细的调试日志)
curl --trace trace.log https://example.com
其它高级选项
-
--proxy:使用代理服务器(格式:host:port,支持 HTTP/SOCKS5)
curl --proxy 127.0.0.1:8080 https://example.com
-
--insecure, -k:忽略 HTTPS 证书验证(不安全,仅用于测试)
curl -k https://self-signed.example.com
-
--user, -u:基本认证(用户名:密码)
curl -u admin:password123 https://auth.example.com
-
--ntlm:使用 NTLM 认证(Windows 域环境)
curl --ntlm -u domain\user:password https://intranet.example.com
-
--limit-rate:限制传输速度(如 100k 表示 100KB/s)
curl --limit-rate 100k https://example.com/big-file.zip
-
--retry:失败后重试次数(网络波动时有用)
curl --retry 5 https://flaky-api.example.com
-
--range:断点续传(请求部分内容,用于下载大文件)
curl --range 0-1024 https://example.com/large-file.zip
-
-x, --compressed:启用压缩(自动处理 gzip/bzip2 等编码)
curl -x https://example.com
常用案例
-
模拟域名访问
作用:请求 192.0.2.1,但告诉服务器 "我是 fake.example.com"
curl -H "Host: fake.example.com" http://192.0.2.1
-
下载文件
短选项 -o,指定输出文件名
curl -o filename.html https://example.com/page.html
大写 -O,使用 URL 中的文件名
curl -O https://example.com/filename.zip
常用案例持续更新中...