【问题标题】:python HTTP multipart header value changed after using urllib.request.Request()使用 urllib.request.Request() 后 python HTTP 多部分标头值更改
【发布时间】:2012-12-18 17:43:43
【问题描述】:

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

【问题讨论】:

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


    【解决方案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好像支持,虽然我没用过。

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-19
        • 1970-01-01
        • 2016-11-19
        • 2014-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多