【问题标题】:How to HTTP 'Keep-Alive' in Python3.2 with urllib如何使用 urllib 在 Python3.2 中 HTTP 'Keep-Alive'
【发布时间】:2013-11-14 12:25:06
【问题描述】:

我尝试使用以下代码在 Python 3.2.3 中保持与 urllib.request 的 HTTP 连接:

handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(handler)
opener.addheaders = [("connection", "keep-alive"), ("Cookie", cookie_value)]
r = opener.open(url)

但是,如果我使用 Wireshark 收听连接,我会得到一个带有“连接:已关闭”但设置 Cookie 的标题。

Host: url
Cookie: cookie-value
Connection: close

如何将 Headerinfo 设置为 Connection: keep-alive?

【问题讨论】:

    标签: urllib python-3.2


    【解决方案1】:

    我通过使用http-client保持连接状态

    import http.client
    conn = http.client.HTTPConnection(host, port)
    conn.request(method, url, body, headers)
    

    headers 只是给出 dict,body 仍然可以使用urllib.parse.urlencode。 所以,你可以通过http客户端制作Cookie头。

    参考:
    official reference

    【讨论】:

      【解决方案2】:

      如果您需要比普通 http.client 更自动化的东西,这可能会有所帮助,尽管它不是线程安全的。

      from http.client import HTTPConnection, HTTPSConnection
      import select
      connections = {}
      
      
      def request(method, url, body=None, headers={}, **kwargs):
          scheme, _, host, path = url.split('/', 3)
          h = connections.get((scheme, host))
          if h and select.select([h.sock], [], [], 0)[0]:
              h.close()
              h = None
          if not h:
              Connection = HTTPConnection if scheme == 'http:' else HTTPSConnection
              h = connections[(scheme, host)] = Connection(host, **kwargs)
          h.request(method, '/' + path, body, headers)
          return h.getresponse()
      
      
      def urlopen(url, data=None, *args, **kwargs):
          resp = request('POST' if data else 'GET', url, data, *args, **kwargs)
          assert resp.status < 400, (resp.status, resp.reason, resp.read())
          return resp
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-26
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 2012-03-31
        相关资源
        最近更新 更多