curl命令
curl 是常用的命令行工具,用来请求 Web 服务器。它的名字就是客户端(client)的 URL 工具的意思。
它的功能非常强大,命令行参数多达几十种。如果熟练的话,完全可以取代 Postman 这一类的图形界面工具。
向www.example.com发出 GET 请求,服务器返回的内容会在命令行输出。
curl https://www.example.com
上面命令会生成一个标头Cookie: foo=bar,向服务器发送一个名为foo、值为bar的 Cookie。
curl -b 'foo1=bar;foo2=bar2' https://google.com
上面命令读取本地文件cookies.txt,里面是服务器设置的 Cookie(参见-c参数),将其发送到服务器。
curl -b cookies.txt https://www.google.com
上面命令将服务器的 HTTP 回应所设置 Cookie 写入文本文件cookies.txt。
curl -c cookies.txt https://www.google.com
使用-d参数以后,HTTP 请求会自动加上标头Content-Type : application/x-www-form-urlencoded。并且会自动将请求转为 POST 方法,因此可以省略-X POST。
curl -d'login=emma&password=123'-X POST https://google.com/login
上面命令读取data.txt文件的内容,作为数据体向服务器发送。
curl -d ‘@data.txt’ https://google.com/login
–data-urlencode参数等同于-d,发送 POST 请求的数据体,区别在于会自动将发送的数据进行 URL 编码。上面代码中,发送的数据hello world之间有一个空格,需要进行 URL 编码。
curl --data-urlencode 'comment=hello world' https://google.com/login
-O参数将服务器回应保存成文件,并将 URL 的最后部分当作文件名。 以上命令就是下载math-game.jar文件到当前文件夹
curl -O https://arthas.aliyun.com/math-game.jar
-v参数输出通信的整个过程,用于调试。
curl -v https://www.example.com
参考资料
https://www.ruanyifeng.com/blog/2011/09/curl.html
https://www.ruanyifeng.com/blog/2019/09/curl-reference.html