How to HTTP 'Keep-Alive' in Python3.2 with urllib
Asked Answered
L

2

7

I try to keep a HTTP Connection with urllib.request in Python 3.2.3 alive with this code:

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

But if I listen to the connection with Wireshark I get an Header with "Connection: closed" but set Cookie.

Host: url
Cookie: cookie-value
Connection: close

What do I have to do to set Headerinfo to Connection: keep-alive?

Lattimore answered 3/11, 2013 at 21:26 Comment(0)
I
1

I keep connection alive by use http-client

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

the headers just give dict and body still can use urllib.parse.urlencode. so, you can make Cookie header by http client.

reference:
official reference

Insignia answered 9/11, 2013 at 3:59 Comment(0)
R
1

If you need something more automatic than plain http.client, this might help, though it's not threadsafe.

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
Ratio answered 23/11, 2014 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.