57-http-10-curl命令行

概述

curl是一种命令行工具,作用是发出网络请求,然后得到和提取数据,显示在"标准输出"(stdout)上面。

一、查看网页源码

直接在curl命令后加上网址,就可以看到网页源码。我们以网址baidu.com为例(选择该网址,主要因为它的网页代码较短):

curl baidu.com
<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>

页面会重定向到百度

如果要把这个网页保存下来,可以使用-o参数,这就相当于使用wget命令了。

curl -o [文件名] baidu.com
curl -o baudu.html baidu.com

二、显示头信息

-i参数可以显示http response的头信息,连同网页代码一起。

-I参数则是只显示http response的头信息。

curl -i baidu.com
HTTP/1.1 200 OK                                                   
Date: Sun, 06 Jun 2021 08:49:54 GMT                               
Server: Apache                                                    
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT                      
ETag: "51-47cf7e6ee8400"                                          
Accept-Ranges: bytes                                              
Content-Length: 81                                                
Cache-Control: max-age=86400                                      
Expires: Mon, 07 Jun 2021 08:49:54 GMT                            
Connection: Keep-Alive                                            
Content-Type: text/html                                           
                                                                  
<html>                                                            
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/"> 
</html>                                                           

三、显示通信过程

-v参数可以显示一次http通信的整个过程,包括端口连接和http request头信息。

curl -v baidu.com
* Rebuilt URL to: baidu.com/
*   Trying 220.181.38.148...
* TCP_NODELAY set
* Connected to baidu.com (220.181.38.148) port 80 (#0)
> GET / HTTP/1.1
> Host: baidu.com
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sun, 06 Jun 2021 08:53:20 GMT
< Server: Apache
< Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
< ETag: "51-47cf7e6ee8400"
< Accept-Ranges: bytes
< Content-Length: 81
< Cache-Control: max-age=86400
< Expires: Mon, 07 Jun 2021 08:53:20 GMT
< Connection: Keep-Alive
< Content-Type: text/html
<
<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>
* Connection #0 to host baidu.com left intact

如果你觉得上面的信息还不够,那么下面的命令可以查看更详细的通信过程。

curl --trace output.txt baidu.com
curl --trace-ascii output.txt baidu.com

推荐阅读

阮一峰

http://www.ruanyifeng.com/blog/2019/09/curl-reference.html