CURL笔记-基本使用
CURL命令行使用笔记。
注意事项
- 网址需要用引号扩起来,否则其中的一些字符串(比如
&)会被Bash解析掉
设置请求方法
- 默认是GET方法
- 设置为HEAD方法
-I, --head - 设置为特定方法
-X, --request <command>
设置Header
- 设置头部
-H, --header <header> - 设置
User-Agent头部-A, --user-agent <agent string> - 设置
Cookie头部-b, --cookie <name=data> - 设置
Referer头部-e, --referer <URL>
1 | $ curl -H 'Host: 111.111.11.11'-H 'Accept-Language: es' http://test.com |
curl会默认携带一些Header,比如Content-Type,User-Agent,Accept,如果不想要这些头部,可以:
1 | # 不要携带Content-Type头部 |
设置请求体
-d, --data <data>设置请求体。--data-ascii <data>-d, --data的别名--data-binary <data>与与-d, --data类似,如果以@开头,则后面必须跟着文件名,并且文件中的换行符,回车符会保留,也不会做其他的转换--data-raw <data>与-d, --data类似,只是不会处理参数中的@符号--data-urlencode <data>
需要注意,--data系列参数会把请求的Content-Type设置为application/x-www-form-urlencoded。
-F, --form <name=content>设置表单内容,可以让curl发送和网页中表单一样的请求体,可以用来上传文件,Content-Type头部会被设置为multipart/form-data。
需要注意,--data系列参数和-F参数都会让请求方法变为POST。
设置请求体是curl中比较复杂的操作,这里做了几个实验:
test.txt的内容为:
1 | 123 |
@开头加文件名会让curl使用文件内容。--data默认会去掉回车和换行:
1 | $ curl --data "@test.txt" 'http://localhost:8080/upload' |
--data-binary不会去掉文件中的回车和换行:
1 | $ curl --data-binary "@test.txt" 'http://localhost:8080/upload' |
--data-raw则不会去解析@:
1 | $ curl --data-raw "@test.txt" 'http://localhost:8080/upload' |
--data不会对参数进行url编码:
1 | $ curl --data "你" 'http://localhost:8080/upload' |
这里的..其实是你这个字的原始编码:

--data-urlencode会对参数进行url编码:
1 | $ curl --data-urlencode "你" 'http://localhost:8080/upload' |
一个常见的需求,我们怎么用curl发送JSON请求呢?
1 | $ curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/api/login |
控制输出
- 在输出中包含Header信息
-i, --include(和-I要区分开,后者是发起HEAD请求) - 只输出Header信息
Linux:curl -s -D - www.test.org -o /dev/null
Windows:curl -s -D - www.test.org -o $null
另外一种做法:curl -I -X GET www.test.org
其他
- 调试模式,输出详细信息
-v, --verbose - 自动跳转(跟踪302)
-L, --location
参考资料
如果觉得文章对你有帮助,就打赏杯咖啡钱呗😊

