python - HTTP/1.1 中的 400 Bad Request 但 HTTP/1.0 中没有

标签 python http http-headers httprequest

我正在尝试向这个 url 发送一个 HEAD 请求:

http://ubuntu-releases.mirror.net.in/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso

并获取文件的大小。我当前的 head 请求如下所示:

head_request = "HEAD " + file_path + " HTTP/1.0%s" % ('\r\n\r\n')
socket.socket(socket.AF_INET, socket.SOCK_STREAM).send(head_request)

其中 file_path"/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso"。这非常有效,但是当我用 1.1 替换 1.0 时,我得到了一个 400 HTTP Bad Request

head_request = "HEAD " + file_path + " HTTP/1.1%s" % ('\r\n\r\n')

为什么会这样?

最佳答案

在 HTTP/1.1 中,您必须提供 Host: header 。

使用 netcat (nc) 实用程序的演示:

$ nc ubuntu-releases.mirror.net.in 80 <<END
HEAD /releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso HTTP/1.0

END
HTTP/1.1 200 OK
Date: Sat, 04 Mar 2017 07:25:22 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Wed, 15 Feb 2017 21:44:24 GMT
ETag: "5ca30000-5489895805e00"
Accept-Ranges: bytes
Content-Length: 1554186240
Connection: close
Content-Type: application/x-iso9660-image

$ nc ubuntu-releases.mirror.net.in 80 <<END
HEAD /releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso HTTP/1.1

END

HTTP/1.1 400 Bad Request
Date: Sat, 04 Mar 2017 07:25:33 GMT
Server: Apache/2.4.18 (Ubuntu)
Connection: close
Content-Type: text/html; charset=iso-8859-1

$ nc ubuntu-releases.mirror.net.in 80 <<END
HEAD /releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso HTTP/1.1
Host: ubuntu-releases.mirror.net.in

END

HTTP/1.1 200 OK
Date: Sat, 04 Mar 2017 07:27:27 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Wed, 15 Feb 2017 21:44:24 GMT
ETag: "5ca30000-5489895805e00"
Accept-Ranges: bytes
Content-Length: 1554186240
Content-Type: application/x-iso9660-image

关于python - HTTP/1.1 中的 400 Bad Request 但 HTTP/1.0 中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42593282/

相关文章:

python - 一次 append 多个 pandas 数据帧

python - 使用 pandas 在单个 groupby 调用中执行多个操作?

php - flock 处理时会发生什么?

http - 如何产生501错误?

google-chrome - 覆盖 HTTP 响应中的 "cache-control"值

java - Spring HttpHeaders - 获取授权 header

python - 使用 scipy interpolate griddata 方法重新网格化数据时出现意外的内存错误

python - 在 flask-security 中设置默认角色

http - 赛璐珞和高性能 HTTP 请求

c# - 向 Stripe 发出原始 HTTP POST 请求时如何发送 Stripe 的 key