使用urllib.request.Request()后,python HTTP多部分头值发生了变化

时间:2012-12-18 17:43:43

标签: python http python-3.x http-headers

发送HTTP POST时,设置为keep-alive的标题“connection”值在传出数据包中变为“close”。

这是我正在使用的标题:

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数据包时,我可以看到连接字段变为“关闭”而不是预期的“保持活动”。这是怎么回事?

2 个答案:

答案 0 :(得分: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似乎支持它,尽管我没有使用它。

答案 1 :(得分: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(...

请参阅Persistence of urllib.request connections to a HTTP server