如何向 pycurl 发出 HEAD 请求

How make HEAD request to pycurl

我需要使用 pycurl 发送 HTTP HEAD 请求。

这个代码

curl = pycurl.Curl()
...
curl.setopt(curl.CUSTOMREQUEST, "HEAD")
curl.perform()

产生错误:

< HTTP/1.1 200 OK
* Server nginx/1.6.2 is not blacklisted
< Server: nginx/1.6.2
< Date: # No matters
< Content-Type: text/html; charset=utf-8
< Connection: keep-alive
< Cache-Control: no-cache,no-store,must-revalidate
< Pragma: no-cache
< Expires: # No matters
< Last-Modified: # No matters
< Content-Security-Policy: # No matters
< X-Frame-Options: SAMEORIGIN
< X-XSS-Protection: # No matters
< X-Content-Type-Options: nosniff
< Content-Encoding: gzip
* no chunk, no close, no size. Assume close to signal end
< 
* Operation timed out after 15001 milliseconds with 0 bytes received
* Closing connection 1

有人能帮帮我吗?

您需要 NOBODY 选项。请不要 body。仅更改 CUSTOMREQUEST 不会使 libcurl 更改其行为方式,它会认为它执行 GET,但您将其更改为 HEAD,然后事情就会变糟。

澄清一下。您无需提出自定义请求!仅仅指定一个 'NOBODY' 选项就足以让 pycurl 自己生成一个 'HEAD' 请求。使用 PycURL/7.43.0 libcurl/7.51.0

测试