本篇文章包含了curl的常用案例使用。
如果想了解curl选项的详细说明,请参考前一篇文章「Linux curl 命令详解」。
常见网页访问示例
基本用法
访问一个网页
curl https://www.baidu.com
执行后,相关的网页信息会打印出来
进度条展示
有时候我们不需要进度表展示,而需要进度条展示。比如:下载文件时。
可以通过 -#, --progress-bar 选项实现。
[root@iZ28xbsfvc4Z 20190713]# curl https://www.baidu.com | head -n1 # 进度表显示
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 2443 100 2443 0 0 11662 0 --:--:-- --:--:-- --:--:-- 11688
<!DOCTYPE html>
[root@iZ28xbsfvc4Z 20190713]# curl -# https://www.baidu.com | head -n1 # 进度条显示
######################################################################## 100.0%
<!DOCTYPE html>
静默模式与错误信息打印
当我们做一些操作时,可能会出现进度表。这时我们可以使用 -s, --silent 静默模式去掉这些不必要的信息。
如果使用 -s, --silent 时,还需要打印错误信息,那么还需要使用 -S, --show-error 选项。
静默模式示例
[root@iZ28xbsfvc4Z ~]# curl https://www.baidu.com | head -n1
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 2443 100 2443 0 0 11874 0 --:--:-- --:--:-- --:--:-- 11859
<!DOCTYPE html>
[root@iZ28xbsfvc4Z ~]# curl -s https://www.baidu.com | head -n1
<!DOCTYPE html>
静默模式结合错误信息打印
[root@iZ28xbsfvc4Z 20190713]# curl -s https://140.205.16.113/
[root@iZ28xbsfvc4Z 20190713]#
[root@iZ28xbsfvc4Z 20190713]# curl -sS https://140.205.16.113/
curl: (51) Unable to communicate securely with peer: requested domain name does not match the server's certificate.
显示详细操作信息
使用 -v, --verbose 选项实现。
以 > 开头的行表示curl发送的"header data";< 表示curl接收到的通常情况下隐藏的"header data";而以 * 开头的行表示curl提供的附加信息。
[root@iZ28xbsfvc4Z 20190712]# curl -v https://www.baidu.com
* About to connect() to www.baidu.com port 443 (#0)
* Trying 180.101.49.12...
* Connected to www.baidu.com (180.101.49.12) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate:
* subject: CN=baidu.com,O="Beijing Baidu Netcom Science Technology Co., Ltd",OU=service operation department,L=beijing,ST=beijing,C=CN
* start date: May 09 01:22:02 2019 GMT
* expire date: Jun 25 05:31:02 2020 GMT
* common name: baidu.com
* issuer: CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.baidu.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
< Connection: Keep-Alive
< Content-Length: 2443
< Content-Type: text/html
< Date: Fri, 12 Jul 2019 08:26:23 GMT
< Etag: "588603eb-98b"
< Last-Modified: Mon, 23 Jan 2017 13:23:55 GMT
< Pragma: no-cache
< Server: bfe/1.0.8.18
< Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
<
<!DOCTYPE html>
……………… # curl 网页的具体信息
指定访问的请求方法
当然curl默认使用GET方式访问。使用了 -d, --data <data> 选项,那么会默认为 POST方法访问。如果此时还想实现 GET 访问,那么可以使用 -G, --get 选项强制curl 使用GET方法访问。
同时 -X, --request <command> 选项也可以指定访问方法。