0

发送 HTTP POST 时,设置为 keep-alive 的标头“连接”值在传出数据包中变为“关闭”。

这是我正在使用的标题:

multipart_header = {        
                        'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Firefox/17.0',
                        'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                        'accept-language':'en-US,en;q=0.5',
                        'accept-encoding':'gzip, deflate',
                        'connection':'keep-alive',

                        'content-type':'multipart/form-data; boundary='+boundary,
                        'content-length':''
        }


## command to send the header: 
urllib.request.Request('http://localhost/api/image/upload', data=byte_data, headers=multipart_header)

当我捕获 POST 数据包时,我可以看到连接字段变为“关闭”而不是预期的“保持活动”。这里发生了什么?

4

2 回答 2

1

http://docs.python.org/dev/library/urllib.request.html说:

urllib.request 模块使用 HTTP/1.1 并在其 HTTP 请求中包含 Connection:close 标头。

大概这是有道理的 - 我假设 urllib.request 没有任何功能来实际存储 TCP 套接字以实现真正的 keepalive 连接,因此您不能覆盖此标头。

https://github.com/kennethreitz/requests似乎支持它,虽然我没有使用过这个。

于 2012-12-19T08:58:22.697 回答
0

urllib不支持持久连接。如果您已经有要发送的标头和数据,那么您可以使用http.client重用 http 连接:

from http.client import HTTPConnection

conn = HTTPConnection('localhost', strict=True)
conn.request('POST', '/api/image/upload', byte_data, headers)
r = conn.getresponse()
r.read() # should read before sending the next request
# conn.request(...

请参阅urllib.request 连接到 HTTP 服务器的持久性

于 2012-12-19T09:55:59.077 回答