0 前言
curl是Linux中的一款综合性网络传输工具,既可以上传也可以下载,支持HTTP、HTTPS、FTP等30余种常见协议。
该命令选项超多,在学习笔记68中,我们列举了该命令的部分实例,今天继续通过实例来研究curl命令的功能和用法。
1 curl命令应用实例
1.1 跟随重定向:curl -L 统一资源定位符
在访问一个网页时,如果这个网页已经移动到另一个站点时,会发送一个HTTP Loaction header作为请求,然后将请求重定向到新的地址上。
然而curl在默认情况下不会发送HTTP Location headers(重定向),这时我们可以指定 -L 选项来跟随重定向。
例如,我们打开g.cn时会自动重定向跳转到 google.cn。
当我们使用命令 curl g.cn时,看到的是g.cn的代码。
要想看到google.cn的代码,可以在命令中指定-L选项,即 curl -L g.cn
1.2 断点续传:curl -C - -O 统一资源定位符
在Windows中,我们可以使用迅雷等的软件进行断点续传。
在Linux中,curl可以通过-C选项同样可以达到相同的断点续传效果。
我们以下载 QQ Linux版 文件 https://dldir1.qq.com/qqfile/qq/QQNT/Linux/QQ_3.2.12_240808_amd64_01.deb 为例。
说明:
1.使用ls命令查看当前目录内容,只有一个Code目录。
2.使用 curl -C https://dldir1.qq.com/qqfile/qq/QQNT/Linux/QQ_3.2.12_240808_amd64_01.deb 命令开始下载文件,文件大小是145MB。
3.在下载进度达到19%时,按Ctrl + c 终止下载
4. 使用ls命令查看当前目录内容,除了之前已经存在的Code目录,还多了一个文件QQ_3.2.12_240808_amd64_01.deb。
5.使用du命令查看文件QQ_3.2.12_240808_amd64_01.deb的大小,只有22528KB(19M)。
6.使用命令curl -C - -O https://dldir1.qq.com/qqfile/qq/QQNT/Linux/QQ_3.2.12_240808_amd64_01.deb开始断点续传
7.使用使用ls命令查看当前目录内容,仍然只有Code目录和文件QQ_3.2.12_240808_amd64_01.deb。
8.使用du命令查看文件QQ_3.2.12_240808_amd64_01.deb的大小,有148708KB,即145MB。
1.3 使用代理:curl -x 代理服务器地址:端口 统一资源定位符
在很多时候,上网需要用到代理服务器(比如是使用代理服务器上网或者因为使用curl别人网站而被别人屏蔽IP地址的时候),幸运的是curl提供了-x选项来支持我们设置代理
1.4 指定浏览器类型和版本:curl -A "浏览器User-Agent" 统一资源定位符
有些网站需要使用特定的浏览器去访问,有些还需要使用某些特定的版本。curl提供的-A选项可以让我们指定浏览器类型和版本去访问网站。
我们以访问cs.net为例。
1.4.1 正常访问:curl | more
从反馈的网页代码来看,网页是可以正常浏览的。
1.4.2 指定 使用微软IE 6.0 访问:curl -A "Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 5.2)"
2001年,微软公司推出了IE浏览器最“经典”的6.0版本,并在2003年走上巅峰,IE浏览器各个版本占据全球市场95%的份额。那是IE浏览器的黄金时代。
时过境迁,微软IE 6.0 是很古老的浏览器了,cs.net应该不再支持它了,所以返回的代码跟1.4.1不同。