> curl https://json.im
> curl -I https://json.im
HTTP/1.1 200 OK
Server: openresty
Date: Fri, 04 Jun 2021 07:38:32 GMT
Content-Type: text/html
Content-Length: 12864
Last-Modified: Thu, 29 Apr 2021 01:39:01 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: "608a0e35-3240"
Expires: Fri, 04 Jun 2021 08:38:32 GMT
Cache-Control: max-age=3600
Accept-Ranges: bytes
> curl -i https://json.im
我们可以使用 > 符号将输出重定向到本地文件中。
> curl https://json.im > index.html
也可以通过 curl 自带的 -o/-O 选项将内容保存到文件中。
> curl -o index.html https://json.im
> curl -O https://json.im/index.html
注意:使用 -O 选项时,必须确保链接末尾包含文件名,否则 curl 无法正确保存文件。如果遇到链接中无文件名的情况,应该使用 -o 选项手动指定文件名,或使用重定向符号
我们可以使用
-o
或-O
选项来同时指定多个链接,按照以下格式编写命令:
> curl -O html https://json.im/1.html -O html https://json.im/2.html
> curl -o p1.html https://json.im/1.html -o p2.html https://json.im/2.html
如果直接使用 curl 打开某些被重定向后的链接,这种情况下就无法获取我们想要的网页内容。例如:
> curl http://json.im
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>openresty</center>
</body>
</html>
而当我们通过浏览器打开该链接时,会自动跳转到
https://json.im
。此时我们想要 curl 做的,就是像浏览器一样跟随链接的跳转,获取最终的网页内容。我们可以在命令中添加 -L 选项来跟随链接重定向:
> curl -L http://json.im
我们可以使用 -A 来自定义用户***,例如下面的命令将伪装成安卓火狐浏览器对网页进行请求:
> curl -A "Mozilla/5.0 (Android; Mobile; rv:35.0) Gecko/35.0 Firefox/35.0" https://json.im
当我们需要传递特定的 header 的时候,可以仿照以下命令来写:
> curl -H "Referer: https://rumenz.com" -H "User-Agent: Custom-User-Agent" https://json.im
header 中传递 Cookie
> curl -H "Cookie: JSESSIONID=xxx" https://json.im
-c
保存Cookie
使用 cURL 访问页面的时候,默认是不会保存 Cookie 的curl -c "cookie.txt" https://json.im
> curl -b "cookie.txt" https://json.im
-d
发送POST
请求有一个登录页面 https://json.im/login,只需要提交用户名和密码便可登录。我们可以使用 cURL 来完成这一 POST 请求,-d 用于指定发送的数据,-X 用于指定发送数据的方式
> curl -d "userName=rumenz&passwd=123456" -X POST https://json.im/login
在使用 -d 的情况下,如果省略 -X,则默认为 POST 方式:
> curl -d "userName=rumenz&passwd=123456" https://json.im/login
从文件中读取
data.txt
文本
> curl -d "@data.txt" https://json.im/upload
> curl -C - -O https://json.im/jdk.tar.gz
如果将curl与xargs结合使用,则可以从文件中的URL列表中下载文件。xargs -n 1 curl -O < urls.txt
> curl https://json.im/ -U user:password -x 127.0.0.1:3128
如果您的代理不需要身份验证,您可以跳过-U user:password 。
比如Nginx配置代理
server {
listen 3128;
resolver 8.8.8.8;
proxy_connect;
proxy_connect_allow 443 563;
proxy_connect_connect_timeout 10s;
proxy_connect_read_timeout 10s;
proxy_connect_send_timeout 10s;
location / {
proxy_pass http://$host;
proxy_set_header Host $host;
}
}
> curl -u username:password -T jdk.tar.gz ftp://json.im
> curl --resolve json.im:443:127.0.0.1 https://json.im:443/
对
https://json.im
的查询将告诉curl
从127.0.0.1
请求该站点,而不是使用DNS或/etc/hosts
文件。
> curl --limit-rate 100K https://json.im/jdk.tar.gz -O
有些网域需要HTTP认证,这时curl需要用到--user参数。
> curl --user name:passwd https://json.im
原文链接:https://rumenz.com/rumenbiji/linux-curl-skills.html
微信公众号:入门小站
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。