http.client — HTTP protocol client

Código fuente: Lib/http/client.py


Este módulo define clases que implementan el lado del cliente de los protocolos HTTP y HTTPS. Normalmente no se usa directamente — el módulo urllib.request lo usa para gestionar URLs que utilizan HTTP y HTTPS.

Ver también

The Requests package is recommended for a higher-level HTTP client interface.

Nota

El soporte HTTPS solo está disponible si Python se compiló con soporte SSL (a través del módulo ssl).

Availability: not WASI.

This module does not work or is not available on WebAssembly. See Plataformas WebAssembly for more information.

El módulo proporciona las siguientes clases:

class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192, max_response_headers=None)

An HTTPConnection instance represents one transaction with an HTTP server. It should be instantiated by passing it a host and optional port number. If no port number is passed, the port is extracted from the host string if it has the form host:port, else the default HTTP port (80) is used. If the optional timeout parameter is given, blocking operations (like connection attempts) will timeout after that many seconds (if it is not given, the global default timeout setting is used). The optional source_address parameter may be a tuple of a (host, port) to use as the source address the HTTP connection is made from. The optional blocksize parameter sets the buffer size in bytes for sending a file-like message body. The optional max_response_headers parameter sets the maximum number of allowed response headers to help prevent denial-of-service attacks, otherwise the default value (100) is used.

Por ejemplo, las siguientes llamadas crean instancias que se conectan al servidor en el mismo host y puerto:

>>> h1 = http.client.HTTPConnection('www.python.org')
>>> h2 = http.client.HTTPConnection('www.python.org:80')
>>> h3 = http.client.HTTPConnection('www.python.org', 80)
>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)

Distinto en la versión 3.2: source_address fue adicionado.

Distinto en la versión 3.4: Se eliminó el argumento strict. Las «Respuestas Simples» de estilo HTTP 0.9 ya no son compatibles.

Distinto en la versión 3.7: argumento blocksize fue adicionado.

Distinto en la versión 3.15: max_response_headers parameter was added.

class http.client.HTTPSConnection(host, port=None, *, [timeout, ]source_address=None, context=None, blocksize=8192, max_response_headers=None)

Una subclase de HTTPConnection que usa SSL para la comunicación con servidores seguros. El puerto predeterminado es 443. Si se especifica context, debe ser una instancia de ssl.SSLContext que describa las diversas opciones de SSL.

Por favor lea Consideraciones de seguridad para obtener más información sobre las mejores prácticas.

Distinto en la versión 3.2: source_address, context y check_hostname fueron adicionados.

Distinto en la versión 3.2: This class now supports HTTPS virtual hosts if possible (that is, if ssl.HAS_SNI is true).

Distinto en la versión 3.4: Se eliminó el argumento strict. Las «Respuestas Simples» de estilo HTTP 0.9 ya no son compatibles.

Distinto en la versión 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

Distinto en la versión 3.8: Esta clase ahora habilita TLS 1.3 ssl.SSLContext.post_handshake_auth para el context predeterminado o cuando cert_file se pasa con un context personalizado.

Distinto en la versión 3.10: This class now sends an ALPN extension with protocol indicator http/1.1 when no context is given. Custom context should set ALPN protocols with set_alpn_protocols().

Distinto en la versión 3.12: The deprecated key_file, cert_file and check_hostname parameters have been removed.

Distinto en la versión 3.15: max_response_headers parameter was added.

class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)

Clase cuyas instancias se retornan tras una conexión exitosa. No son instancias realizadas directamente por el usuario.

Distinto en la versión 3.4: Se eliminó el argumento strict. Las «Respuestas Simples» del estilo HTTP 0.9 ya no están soportadas.

Este módulo proporciona la siguiente función:

http.client.parse_headers(fp)

Parse the headers from a file pointer fp representing a HTTP request/response. The file has to be a BufferedIOBase reader (i.e. not text) and must provide a valid RFC 5322 style header.

Esta función retorna una instancia de http.client.HTTPMessage que contiene los campos de encabezado, pero no un payload (lo mismo que HTTPResponse.msg y http.server.BaseHTTPRequestHandler.headers ) Después de regresar, el puntero de archivo fp está listo para leer el cuerpo HTTP.

Nota

parse_headers() no analiza la línea de inicio de un mensaje HTTP; solo analiza las líneas Name: value. El archivo tiene que estar listo para leer estas líneas de campo, por lo que la primera línea ya debe consumirse antes de llamar a la función.

Las siguientes excepciones son lanzadas según corresponda:

exception http.client.HTTPException

La clase base de las otras excepciones en este módulo. Es una subclase de Exception.

exception http.client.NotConnected

Una subclase de HTTPException.

exception http.client.InvalidURL

Una subclase de HTTPException, es lanzada si se proporciona un puerto y no es numérico o está vacío.

exception http.client.UnknownProtocol

Una subclase de HTTPException.

exception http.client.UnknownTransferEncoding

Una subclase de HTTPException.

exception http.client.UnimplementedFileMode

Una subclase de HTTPException.

exception http.client.IncompleteRead

Una subclase de HTTPException.

exception http.client.ImproperConnectionState

Una subclase de HTTPException.

exception http.client.CannotSendRequest

Una subclase de ImproperConnectionState.

exception http.client.CannotSendHeader

Una subclase de ImproperConnectionState.

exception http.client.ResponseNotReady

Una subclase de ImproperConnectionState.

exception http.client.BadStatusLine

Una subclase de HTTPException. Es lanzada si un servidor responde con un código de estado HTTP que no entendemos.

exception http.client.LineTooLong

Una subclase de HTTPException. Es lanzada si se recibe una línea excesivamente larga en el protocolo HTTP del servidor.

exception http.client.RemoteDisconnected

Una subclase de ConnectionResetError y BadStatusLine. Lanzada por HTTPConnection.getresponse() cuando el intento de leer la respuesta no produce datos leídos de la conexión, indica que el extremo remoto ha cerrado la conexión.

Added in version 3.5: Previamente, BadStatusLine('') fue lanzada.

exception http.client.ProxyTunnelError

A subclass of OSError. Raised when the proxy server answers the CONNECT request sent for HTTPConnection.set_tunnel() with a status other than 200.

code

The HTTP status code of the proxy’s response, such as 407.

reason

The reason phrase of the proxy’s response.

headers

The headers of the proxy’s response, as an http.client.HTTPMessage instance.

Added in version 3.16.0a2 (unreleased): Previously, OSError was raised.

Las constantes definidas en este módulo son:

http.client.HTTP_PORT

El puerto predeterminado para el protocolo HTTP (siempre 80).

http.client.HTTPS_PORT

El puerto predeterminado para el protocolo HTTPS (siempre 443).

http.client.responses

Este diccionario asigna los códigos de estado HTTP 1.1 a los nombres W3C.

Ejemplo: http.client.responses[http.client.NOT_FOUND] es 'Not Found'.

Consulte Códigos de estado HTTP para obtener una lista de los códigos de estado HTTP que están disponibles en este módulo como constantes.

Objetos de HTTPConnection

Las instancias HTTPConnection tienen los siguientes métodos:

HTTPConnection.request(method, url, body=None, headers={}, *, encode_chunked=False, continue_timeout=2.5)

This will send a request to the server using the HTTP request method method and the request URI url. The provided url must be an absolute path to conform with RFC 2616 §5.1.2 (unless connecting to an HTTP proxy server or using the OPTIONS or CONNECT methods).

If body is specified, the specified data is sent after the headers are finished. It may be a str, a bytes-like object, an open file object, or an iterable of bytes. If body is a string, it is encoded as ISO-8859-1, the default for HTTP. If it is a bytes-like object, the bytes are sent as is. If it is a file object, the contents of the file is sent; this file object should support at least the read() method. If the file object is an instance of io.TextIOBase, the data returned by the read() method will be encoded as ISO-8859-1, otherwise the data returned by read() is sent as is. If body is an iterable, the elements of the iterable are sent as is until the iterable is exhausted.

The headers argument should be a mapping of extra HTTP headers to send with the request. A Host header must be provided to conform with RFC 2616 §5.1.2 (unless connecting to an HTTP proxy server or using the OPTIONS or CONNECT methods).

If headers contains neither Content-Length nor Transfer-Encoding, but there is a request body, one of those header fields will be added automatically. If body is None, the Content-Length header is set to 0 for methods that expect a body (PUT, POST, PATCH, and QUERY). If body is a string or a bytes-like object that is not also a file, the Content-Length header is set to its length. Any other type of body (files and iterables in general) will be chunk-encoded, and the Transfer-Encoding header will automatically be set instead of Content-Length.

El argumento encode_chunked solo es relevante si Transfer-Encoding se especifica en headers. Si encode_chunked es False, el objeto HTTPConnection supone que toda la codificación es manejada por el código de llamada. Si es True, el cuerpo estará codificado en fragmentos.

For example, to perform a GET request to https://docs.python.org/3/:

>>> import http.client
>>> host = "docs.python.org"
>>> conn = http.client.HTTPSConnection(host)
>>> conn.request("GET", "/3/", headers={"Host": host})
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200 OK

Nota

La codificación de transferencia fragmentada se ha agregado al protocolo HTTP versión 1.1. A menos que se sepa que el servidor HTTP maneja HTTP 1.1, el llamador debe especificar la longitud del contenido o debe pasar un str o un objeto similar a bytes que no sea también un archivo como la representación del cuerpo.

Nota

Note that you must have read the whole response or call close() if getresponse() raised an non-ConnectionError exception before you can send a new request to the server.

Distinto en la versión 3.2: body ahora puede ser un iterable.

Distinto en la versión 3.6: Si ni Content-Length ni Transfer-Encoding están configurados en headers, el archivo y los objetos iterables body ahora están codificados en fragmentos. Se agregó el argumento encode_chunked. No se intenta determinar la longitud del contenido para los objetos de archivo.

Distinto en la versión 3.16.0a2 (unreleased): The continue_timeout parameter was added.

If the headers include Expect: 100-Continue and body is set, the body will not be sent until either a 100 Continue response is received from the server or continue_timeout seconds have elapsed; if a response code other than 100 is received, the body will not be sent at all.

continue_timeout value must be greater than zero, otherwise ValueError is raised.

Distinto en la versión 3.16.0a2 (unreleased): QUERY was added to the methods that expect a body.

HTTPConnection.getresponse(support_continue=False)

Debe llamarse después de enviar una solicitud para obtener la respuesta del servidor. Retorna una instancia de HTTPResponse.

By default, 100 Continue responses are skipped and the method returns the first response with a status other than 100. If support_continue is true, a 100 Continue response is returned to the caller, which must then send the request body and call getresponse() again to obtain the final response.

Nota

The whole response must be read before a new request can be sent to the server.

Distinto en la versión 3.5: Si una ConnectionError o una subclase fue lanzada, el objeto HTTPConnection estará listo para volver a conectarse cuando se envíe una nueva solicitud.

Note that this does not apply to OSErrors raised by the underlying socket. Instead the caller is responsible to call close() on the existing connection.

Distinto en la versión 3.16.0a2 (unreleased): Added the support_continue parameter. (In prior versions a Continue response was always ignored.)

HTTPConnection.set_debuglevel(level)

Establecer el nivel de depuración. El nivel de depuración predeterminado es 0, lo que significa que no se imprime ninguna salida de depuración. Cualquier valor mayor que 0 hará que todos los resultados de depuración definidos actualmente se impriman en stdout. El debuglevel se pasa a cualquier objeto nuevo HTTPResponse que se cree.

Added in version 3.1.

HTTPConnection.set_tunnel(host, port=None, headers=None)

Configure el host y el puerto para el túnel de conexión HTTP. Esto permite ejecutar la conexión a través de un servidor proxy.

The host and port arguments specify the endpoint of the tunneled connection (i.e. the address included in the CONNECT request, not the address of the proxy server).

The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request. Non-string header values are converted to strings via str().

As HTTP/1.1 is used for HTTP CONNECT tunnelling request, as per the RFC, a HTTP Host: header must be provided, matching the authority-form of the request target provided as the destination for the CONNECT request. If a HTTP Host: header is not provided via the headers argument, one is generated and transmitted automatically.

Por ejemplo, para hacer un túnel a través de un servidor proxy HTTPS que se ejecuta localmente en el puerto 8080, pasaríamos la dirección del proxy al constructor HTTPSConnection, y la dirección del host al que finalmente queremos llegar al método set_tunnel():

>>> import http.client
>>> conn = http.client.HTTPSConnection("localhost", 8080)
>>> conn.set_tunnel("www.python.org")
>>> conn.request("HEAD","/index.html")

Added in version 3.2.

Distinto en la versión 3.12: HTTP CONNECT tunnelling requests use protocol HTTP/1.1, upgraded from protocol HTTP/1.0. Host: HTTP headers are mandatory for HTTP/1.1, so one will be automatically generated and transmitted if not provided in the headers argument.

Distinto en la versión 3.16.0a2 (unreleased): ProxyTunnelError is raised if the proxy rejects the CONNECT request.

HTTPConnection.get_proxy_response_headers()

Returns a dictionary with the headers of the response received from the proxy server to the CONNECT request.

If the CONNECT request was not sent, the method returns None.

Added in version 3.12.

HTTPConnection.connect()

Se conecta al servidor especificado cuando el objeto fue creado. Por defecto, esto se llama automáticamente cuando se realiza una solicitud si el cliente aún no tiene una conexión.

Lanza un evento de auditoría http.client.connect con los argumentos self, host, port.

HTTPConnection.close()

Cierre la conexión al servidor.

HTTPConnection.blocksize

Tamaño del búfer en bytes para enviar un archivo como cuerpo del mensaje.

Added in version 3.7.

HTTPConnection.max_response_headers

The maximum number of allowed response headers to help prevent denial-of-service attacks. By default, the maximum number of allowed headers is set to 100. The same limit applies to the trailer section of a chunked response.

Added in version 3.15.

As an alternative to using the request() method described above, you can also send your request step by step, by using the four functions below.

HTTPConnection.putrequest(method, url, skip_host=False, skip_accept_encoding=False, continue_timeout=2.5)

Esta debería ser la primera llamada después de que se haya realizado la conexión al servidor. Envía una línea al servidor que consta de la cadena de caracteres method, la cadena de caracteres url y la versión HTTP (HTTP/1.1). Para deshabilitar el envío automático de encabezados Host: o Accept-Encoding: (por ejemplo, para aceptar codificaciones de contenido adicionales), especifique skip_host o skip_accept_encoding con valores no Falsos.

If an Expect: 100-Continue header is sent, the optional continue_timeout parameter sets how many seconds the client will wait for a 100 Continue response before sending the message body, It must be greater than zero, otherwise ValueError is raised.

Distinto en la versión 3.16.0a2 (unreleased): continue_timeout parameter was added.

HTTPConnection.putheader(header, argument[, ...])

Envía un encabezado de estilo RFC 822al servidor. Este envía una línea al servidor que consta del encabezado, dos puntos y un espacio, y el primer argumento. Si se dan más argumentos, se envían líneas de continuación, cada una de las cuales consta de tabulación y un argumento.

HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)

Send a blank line to the server, signalling the end of the headers. The optional message_body argument can be used to pass a message body associated with the request. If a body is provided and an Expect: 100-Continue header has been sent, the body will not be sent until a 100 Continue response is received from the server; if another response code is received, the body is not sent at all. If no response is received within the continue_timeout given to putrequest(), the body will be sent regardless.

Si encode_chunked es True, el resultado de cada iteración de message_body se codificará en fragmentos como se especifica en RFC 7230, Sección 3.3.1. La forma en que se codifican los datos depende del tipo de message_body. Si message_body implementa buffer interface la codificación dará como resultado un solo fragmento. Si message_body es una collections.abc.Iterable, cada iteración de message_body dará como resultado un fragmento. Si message_body es un objeto file object, cada llamada a .read() dará como resultado un fragmento. El método señala automáticamente el final de los datos codificados en fragmentos inmediatamente después de message_body.

Nota

Debido a la especificación de codificación fragmentada, fragmentos vacíos producidos por un cuerpo iterador será ignorado por el codificador de fragmentos. Esto es para evitar la terminación prematura de la lectura de la solicitud por parte del servidor de destino debido a una codificación con formato incorrecto.

Distinto en la versión 3.6: Added chunked encoding support and the encode_chunked parameter.

Distinto en la versión 3.16.0a2 (unreleased): If an Expect: 100-Continue header has been sent, the body will not be sent until a 100 Continue response is received from the server, or a contine_timeout has elapsed. If the response code is not 100, the body will not be sent at all.

HTTPConnection.send(data)

Envía datos al servidor. Esto debe usarse directamente solo después de que se haya llamado al método endheaders() y antes de que se llame al método getresponse().

Lanza un evento de auditoría http.client.send con los argumentos self, data.

Objetos de HTTPResponse

Una instancia de HTTPResponse envuelve la respuesta HTTP del servidor. Proporciona acceso a los encabezados de la solicitud y al cuerpo de la entidad. La respuesta es un objeto iterable y puede usarse en una declaración with.

Distinto en la versión 3.5: La interfaz io.BufferedIOBase ahora está implementada y todas sus operaciones de lectura están soportadas.

HTTPResponse.read([amt])

Lee y retorna el cuerpo de respuesta, o hasta los siguientes bytes amt.

HTTPResponse.readinto(b)

Lee hasta los siguientes bytes len(b) del cuerpo de respuesta en el búfer b. Retorna el número de bytes leídos.

Added in version 3.3.

HTTPResponse.getheader(name, default=None)

Retorna el valor del encabezado name, o default si no hay un encabezado que coincida con name. Si hay más de un encabezado con el nombre name, retorne todos los valores unidos por “, “. Si “default” es cualquier iterable que no sea una sola cadena de caracteres sus elementos se retornan, de manera similar, unidos por comas.

HTTPResponse.getheaders()

Retorna una lista de tuplas (encabezado, valor).

HTTPResponse.fileno()

Retorna el fileno del socket implícito.

HTTPResponse.msg

Una instancia http.client.HTTPMessage que contiene los encabezados de respuesta. http.client.HTTPMessage es una subclase de email.message.Message.

HTTPResponse.version

Versión del protocolo HTTP utilizada por el servidor. 10 para HTTP/1.0, 11 para HTTP/1.1.

HTTPResponse.url

URL del recurso recuperado, comúnmente utilizado para determinar si se siguió una redirección.

HTTPResponse.headers

Cabeceras de la respuesta en forma de una instancia email.message.EmailMessage.

HTTPResponse.status

Código del estado retornado por el servidor.

HTTPResponse.reason

Una frase de la razón es retornada por el servidor.

HTTPResponse.debuglevel

Un depurador. Si debuglevel es mayor que cero, los mensajes se imprimirán en stdout a medida que se lee y analiza la respuesta.

HTTPResponse.closed

Es True si la transmisión está cerrada.

HTTPResponse.geturl()

Obsoleto desde la versión 3.9: Deprecada a favor de url.

HTTPResponse.info()

Obsoleto desde la versión 3.9: Deprecada a favor de headers.

HTTPResponse.getcode()

Obsoleto desde la versión 3.9: Deprecada a favor de status.

Ejemplos

Aquí hay una sesión de ejemplo que usa el método GET method:

>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
200 OK
>>> data1 = r1.read()  # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while chunk := r1.read(200):
...     print(repr(chunk))
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn = http.client.HTTPSConnection("docs.python.org")
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

Aquí hay una sesión de ejemplo que usa el método HEAD. Tenga en cuenta que el método HEAD nunca retorna ningún dato.

>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("HEAD", "/")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b''
True

Aquí hay una sesión de ejemplo que usa el método POST:

>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"}
>>> conn = http.client.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
302 Found
>>> data = response.read()
>>> data
b'Redirecting to <a href="https://bugs.python.org/issue12524">https://bugs.python.org/issue12524</a>'
>>> conn.close()

Las solicitudes HTTP PUT del lado del cliente son muy similares a las solicitudes POST. La diferencia radica solo en el lado del servidor donde los servidores HTTP permitirán que se creen recursos a través de la solicitud PUT. Cabe señalar que los métodos HTTP personalizados también se manejan en urllib.request.Request configurando el atributo de método apropiado. Aquí hay una sesión de ejemplo que muestra cómo enviar una solicitud PUT:

>>> # This creates an HTTP request
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200 OK

Conditional transmission of the body is supported when an Expect: 100-Continue header is set. To use this in a simple case, just set the header, and optionally the time for which the client should wait for a 100 Continue response before sending the body regardless:

>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY, headers={'Expect': '100-Continue'},
...              continue_timeout=1.0)
>>> response = conn.getresponse()
>>> # You will not see the '100' response, as it is handled internally
>>> print(response.status, response.reason)
200, OK

Here is a more complex example in which we manually check the response and decide whether to send the body. This may be useful if the body must be generated by some resource-intensive process which should be skipped if the server will not accept it. continue_timeout does not apply here, so this should only be used with servers known to support Expect: 100-Continue; otherwise getresponse() may block until the connection’s timeout expires.

>>> import http.client
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.putrequest("PUT", "/file")
>>> conn.putheader('Expect', '100-Continue')
>>> # Assuming you know in advance what the length will be
>>> # If not, you will need to encode it as chunked
>>> conn.putheader('Content-Length', '42')
>>> conn.endheaders()
>>> response = conn.getresponse(support_continue=True)
>>> print(response.status, response.reason)
100, Continue
>>> BODY = resource_intensive_calculation()
>>> conn.send(BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK

Objetos de HTTPMessage

class http.client.HTTPMessage(email.message.Message)

Una instancia de http.client.HTTPMessage contiene los encabezados de una respuesta HTTP. Se implementa utilizando la clase email.message.Message.