Bootstrap

curl学习笔记

curl

  • Client URL
  • command line tool and library for transferring data with URLs

Examples

# 获取网页
curl https://www.baidu.com

# 获取响应头+网页
curl https://www.baidu.com

# 获取并保存网页
curl -o filename.txt https://www.baidu.com
# 相当于
wget -O filename.txt https://www.baidu.com

# 发送get请求并携带参数
curl https://jsonplaceholder.typicode.com/posts?userId=1

# post表单信息(Content-Type : application/x-www-form-urlencoded)
curl -X POST --data-urlencode "title=foo&body=bar&userId=1" https://jsonplaceholder.typicode.com/posts

curl -X POST 'https://jsonplaceholder.typicode.com/posts' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'title=foo' \
--data-urlencode 'body=bar' \
--data-urlencode 'userId=1'

Parameters

  • -b参数用来向服务器发送 Cookie
curl -b 'foo=bar' https://google.com
curl -b 'foo1=bar' -b 'foo2=baz' https://google.com
curl -b cookies.txt https://www.google.com
  • -d参数用于发送 POST 请求的数据体
curl -d'login=emma&password=123'-X POST https://google.com/login
curl -d 'login=emma' -d 'password=123' -X POST  https://google.com/login
# 使用-d参数以后,HTTP 请求会自动加上标头Content-Type : application/x-www-form-urlencoded。并且会自动将请求转为 POST 方法,因此可以省略-X POST
curl -d '@data.txt' https://google.com/login
# -d参数可以读取本地文本文件的数据,向服务器发送
  • -G参数用来构造 URL 的查询字符串
curl -G -d 'q=kitties' -d 'count=20' https://google.com/search
curl -G --data-urlencode 'comment=hello world' https://www.example.com # 数据需要 URL 编码
  • -L参数会让 HTTP 请求跟随服务器的重定向
curl 默认不跟随重定向
curl -L -d 'tweet=hi' https://api.twitter.com/tweet
  • -o参数将服务器的回应保存成文件,等同于wget命令
curl -o example.html https://www.example.com
  • -u参数用来设置服务器认证的用户名和密码
curl -u 'bob:12345' https://google.com/login
# 命令设置用户名为bob,密码为12345,然后将其转为 HTTP 标头Authorization: Basic Ym9iOjEyMzQ1
  • -v参数输出通信的整个过程,用于调试
curl -v https://www.example.com

Resources

  • quick ref: https://quickref.me/curl
  • tutorial: https://www.ruanyifeng.com/blog/2011/09/curl.html
  • tutorial: https://www.ruanyifeng.com/blog/2019/09/curl-reference.html
;