12

背景

我一直在通过 CLI 使用和以下工具对一些 HTTP 请求进行time计时:wgetcurl

/usr/bin/time -v wget --spider http://localhost/index
/usr/bin/time -v curl http://localhost/index 2>&1 > /dev/null

我注意到的是,在使用 时curl,我得到的响应时间与wget仅在第​​一个请求中相似,而在后续请求中的响应时间要短得多,好像响应curl是从缓存中提供的,wget但不是。

经过调查,我发现在指定时--spiderwget发出HEAD如下附加的请求,可以解释为什么绕过缓存wget

要求

HEAD /index HTTP/1.0
User-Agent: Wget/1.12 (linux-gnu)
Accept: */*
Host: localhost
Connection: Keep-Alive

回复

HTTP/1.1 200 OK
Date: Mon, 28 Nov 2011 14:45:59 GMT
Server: Apache/2.2.14 (Ubuntu)
Content-Location: index.php
Vary: negotiate,Accept-Encoding
TCN: choice
X-Powered-By: PHP/5.3.2-1ubuntu4.10
Set-Cookie: SESS421aa90e079fa326b6494f812ad13e79=16oqmug3loekjlb1tlvmsrtcr2; expires=Wed, 21-Dec-2011 18:19:19 GMT; path=/
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Mon, 28 Nov 2011 14:45:59 GMT
Cache-Control: store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8

由于我正在做更高级的事情(在单独的文件中编写正文和标题、发布数据、将 cookie 保存在 jar 中......)我需要使用curl而不是wget. 因此,我试图HEADcurl.

问题

我设法发送了一个HEAD请求,curl如下所示:

curl "http://localhost/index" --request "HEAD" -H "Connection: Keep-Alive" -0

要求

HEAD /index HTTP/1.0
User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15
Host: localhost
Accept: */*
Connection: Keep-Alive

回复

HTTP/1.1 200 OK
Date: Mon, 28 Nov 2011 15:44:02 GMT
Server: Apache/2.2.14 (Ubuntu)
Content-Location: index.php
Vary: negotiate,Accept-Encoding
TCN: choice
X-Powered-By: PHP/5.3.2-1ubuntu4.10
Set-Cookie: SESS421aa90e079fa326b6494f812ad13e79=4001hcmhdbnkb9e2v8nok9lii1; expires=Wed, 21-Dec-2011 19:17:22 GMT; path=/
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Mon, 28 Nov 2011 15:44:02 GMT
Cache-Control: store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8

curl尽管请求/响应似乎没问题,但当我在嗅探时执行上述命令时,tcpdump我可以看到服务器立即响应,但是我的curl命令总是保持恰好 15 秒,这显然是一个大问题,因为我正在尝试时间我的curl命令(仅供参考,之前我曾经得到一个curl: (18) transfer closed with 3 bytes remaining to read服务器没有HEAD正确处理并且在Content-Length: 3没有返回任何内容的情况下返回,但没有一切看起来都正常)。

我尝试使用--max-timeand--speed-time参数curl在收到时立即超时,200 OK但这没有区别。

问:如何HEAD以 curl 命令在收到服务器响应后立即停止的方式发送 curl 请求?

4

1 回答 1

23

你为什么不直接使用这个-I选项?

-I/--head
    (HTTP/FTP/FILE) Fetch the HTTP-header only! HTTP-servers feature
    the command HEAD which this uses to get nothing but  the  header
    of  a  document.  When used on a FTP or FILE file, curl displays
    the file size and last modification time only
于 2011-11-28T19:53:10.057 回答