发送HEAD请求时,cURL挂起了15秒钟。

12

背景

我一直在使用命令行界面通过time和一些工具如wgetcurl来计时一些HTTP请求,具体如下:

/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没有这样做。

经过调查,我发现当使用--spider参数时,wget会发送一个如下所示的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中保存信息等...),我需要使用curl而不是wget。因此,我正在尝试使用curl模拟一个HEAD请求。

问题

我已经成功发送了一个curlHEAD请求,如下所示:

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命令(事实上,在服务器没有正确处理HEAD并返回Content-Length: 3而没有返回任何内容时我曾经遇到过curl: (18) transfer closed with 3 bytes remaining to read,但现在一切都看起来很好)。
我尝试使用--max-time--speed-time参数,让curl在收到200 OK后立即超时,但没有任何改变。
问: 如何使用curl发送HEAD请求,以使curl命令在收到来自服务器的响应后立即停止?
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

3
因为我不知道还有这个选项 :) 太好了,这样就可以发送一个 HEAD 命令,并在收到类似于 wget --spider 那样的头信息后停止了。 - Max
5
一种更一般的选项(不是特定于curl的)是发送“Connection: close”标头...而不是keep-alive。-I标志使curl自我短路并关闭连接本身。“Connection: close”告诉服务器在处理请求后关闭连接。“keep-alive”告诉服务器等待更多请求。 :) - jakem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接