Python Glossary Русский

all Python 3http.clientterm

http.client.HTTPConnection

connections

A single HTTP connection to a server: request() sends a request, getresponse() returns the response. The low-level foundation of urllib.request.

Syntax

conn = http.client.HTTPConnection(host, port=None, timeout=..., source_address=None); conn.request(method, url, body=None, headers={}); resp = conn.getresponse()

The host goes without a scheme: HTTPConnection('http://example.com') fails with InvalidURL "nonnumeric port" because everything after the colon is taken as the port. The constructor connects nothing; the connection happens on the first request(), and network errors (ConnectionRefusedError, TimeoutError) come from there. Without a timeout a request can hang forever. Requests on one connection are strictly sequential: read() the response fully before the next request(), or you get ResponseNotReady or CannotSendRequest. 4xx and 5xx codes raise nothing; check resp.status.

Examples

import http.client
conn = http.client.HTTPConnection('example.com', 8080, timeout=5)
print(conn.host, conn.port, conn.sock)  # → example.com 8080 None — соединения ещё нет
try:
    http.client.HTTPConnection('http://example.com')
except http.client.InvalidURL as e:
    print(e)  # → nonnumeric port: '//example.com'
import http.client
import socket
server, client = socket.socketpair()
server.sendall(b'HTTP/1.1 404 Not Found\r\nContent-Length: 4\r\n\r\nnope')
conn = http.client.HTTPConnection('example.com')
conn.sock = client  # вместо сети — заранее записанный ответ
conn.request('GET', '/missing', headers={'Accept': 'text/plain'})
print(server.recv(1024).split(b'\r\n')[0])  # → b'GET /missing HTTP/1.1'
resp = conn.getresponse()
print(resp.status, resp.reason, resp.read())  # → 404 Not Found b'nope'
conn.close()
server.close()

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy