http.client --- HTTP プロトコルクライアント

ソースコード: Lib/http/client.py


このモジュールでは HTTP および HTTPS プロトコルのクライアントサイドを実装しているクラスを定義しています。通常、このモジュールは直接使いません --- urllib.request モジュールが HTTP や HTTPS を使った URL を扱う上でこのモジュールを使います。

参考

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

注釈

HTTPS のサポートは、Python が SSL サポート付きでコンパイルされている場合にのみ利用できます (ssl モジュールによって)。

利用可能性: Emscripten でなく、WASI でもないこと。

このモジュールは WebAssembly プラットフォーム wasm32-emscriptenwasm32-wasi では動作しないか、利用不可です。詳しくは、WebAssemblyプラットフォーム を見てください。

このモジュールでは以下のクラスを提供しています:

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

HTTPConnection インスタンスは、HTTP サーバとの一回のトランザクションを表現します。 インスタンスの生成はホスト名とオプションのポート番号を与えることで行います。 ポート番号を指定しなかった場合、ホスト名文字列が host:port の形式であれば、ホスト名からポート番号を抽出し、そうでない場合には標準の HTTP ポート番号 (80) を使います。 オプションの引数 timeout が渡された場合、ブロックする処理 (コネクション接続など) のタイムアウト時間(秒数)として利用されます (渡されなかった場合は、グローバルのデフォルトタイムアウト設定が利用されます)。 オプションの引数 source_address を (host, port) という形式のタプルにすると HTTP 接続の接続元アドレスとして使用します。 オプションの blocksize 引数は、送信するファイル類メッセージボディのバッファサイズをバイト単位で設定します。

例えば、以下の呼び出しは全て同じサーバの同じポートに接続するインスタンスを生成します:

>>> 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)

バージョン 3.2 で変更: source_address が追加されました。

バージョン 3.4 で変更: strict パラメータは廃止されました。HTTP 0.9 の "シンプルなレスポンス" のような形式はもはやサポートされません。

バージョン 3.7 で変更: blocksize 引数が追加されました。

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

HTTPConnection のサブクラスはセキュア・サーバとやりとりする為の SSL を使う場合に用います。デフォルトのポート番号は 443 です。context が指定されれば、それは様々な SSL オプションを記述する ssl.SSLContext インスタンスでなければなりません。

ベストプラクティスに関するより良い情報が セキュリティで考慮すべき点 にありますのでお読みください。

バージョン 3.2 で変更: source_addresscontext そして check_hostname が追加されました。

バージョン 3.2 で変更: This class now supports HTTPS virtual hosts if possible (that is, if ssl.HAS_SNI is true).

バージョン 3.4 で変更: strict パラメータは廃止されました。HTTP 0.9 の "シンプルなレスポンス" のような形式はもはやサポートされません。

バージョン 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.

バージョン 3.8 で変更: This class now enables TLS 1.3 ssl.SSLContext.post_handshake_auth for the default context or when cert_file is passed with a custom context.

バージョン 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().

バージョン 3.12 で変更: The deprecated key_file, cert_file and check_hostname parameters have been removed.

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

コネクションに成功したときに、このクラスのインスタンスが返されます。ユーザーから直接利用されることはありません。

バージョン 3.4 で変更: strict パラメータは廃止されました。HTTP 0.9 の "シンプルなレスポンス" のような形式はもはやサポートされません。

このモジュールは以下の関数を提供します:

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 2822 style header.

This function returns an instance of http.client.HTTPMessage that holds the header fields, but no payload (the same as HTTPResponse.msg and http.server.BaseHTTPRequestHandler.headers). After returning, the file pointer fp is ready to read the HTTP body.

注釈

parse_headers() does not parse the start-line of a HTTP message; it only parses the Name: value lines. The file has to be ready to read these field lines, so the first line should already be consumed before calling the function.

状況に応じて、以下の例外が送出されます:

exception http.client.HTTPException

このモジュールにおける他の例外クラスの基底クラスです。 Exception のサブクラスです。

exception http.client.NotConnected

HTTPException サブクラスです。

exception http.client.InvalidURL

HTTPException のサブクラスです。ポート番号を指定したものの、その値が数字でなかったり空のオブジェクトであった場合に送出されます。

exception http.client.UnknownProtocol

HTTPException サブクラスです。

exception http.client.UnknownTransferEncoding

HTTPException サブクラスです。

exception http.client.UnimplementedFileMode

HTTPException サブクラスです。

exception http.client.IncompleteRead

HTTPException サブクラスです。

exception http.client.ImproperConnectionState

HTTPException サブクラスです。

exception http.client.CannotSendRequest

ImproperConnectionState のサブクラスです。

exception http.client.CannotSendHeader

ImproperConnectionState のサブクラスです。

exception http.client.ResponseNotReady

ImproperConnectionState のサブクラスです。

exception http.client.BadStatusLine

HTTPException のサブクラスです。サーバが理解できない HTTP 状態コードで応答した場合に送出されます。

exception http.client.LineTooLong

A subclass of HTTPException. Raised if an excessively long line is received in the HTTP protocol from the server.

exception http.client.RemoteDisconnected

A subclass of ConnectionResetError and BadStatusLine. Raised by HTTPConnection.getresponse() when the attempt to read the response results in no data read from the connection, indicating that the remote end has closed the connection.

バージョン 3.5 で追加: Previously, BadStatusLine('') was raised.

このモジュールで定義されている定数は以下の通りです:

http.client.HTTP_PORT

HTTP プロトコルの標準のポート (通常は 80) です。

http.client.HTTPS_PORT

HTTPS プロトコルの標準のポート (通常は 443) です。

http.client.responses

このディクショナリは、HTTP 1.1ステータスコードをW3Cの名前にマップしたものです。

例: http.client.responses[http.client.NOT_FOUND]'Not Found' を示します。

See HTTP ステータスコード for a list of HTTP status codes that are available in this module as constants.

HTTPConnection オブジェクト

HTTPConnection インスタンスには以下のメソッドがあります:

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

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, and PATCH). 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.

The encode_chunked argument is only relevant if Transfer-Encoding is specified in headers. If encode_chunked is False, the HTTPConnection object assumes that all encoding is handled by the calling code. If it is True, the body will be chunk-encoded.

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

注釈

Chunked transfer encoding has been added to the HTTP protocol version 1.1. Unless the HTTP server is known to handle HTTP 1.1, the caller must either specify the Content-Length, or must pass a str or bytes-like object that is not also a file as the body representation.

バージョン 3.2 で変更: body は iterable オブジェクトとして使用できます。

バージョン 3.6 で変更: If neither Content-Length nor Transfer-Encoding are set in headers, file and iterable body objects are now chunk-encoded. The encode_chunked argument was added. No attempt is made to determine the Content-Length for file objects.

HTTPConnection.getresponse()

サーバに対して HTTP 要求を送り出した後に呼び出されなければりません。要求に対する応答を取得します。 HTTPResponse インスタンスを返します。

注釈

すべての応答を読み込んでからでなければ新しい要求をサーバに送ることはできないことに注意しましょう。

バージョン 3.5 で変更: If a ConnectionError or subclass is raised, the HTTPConnection object will be ready to reconnect when a new request is sent.

HTTPConnection.set_debuglevel(level)

Set the debugging level. The default debug level is 0, meaning no debugging output is printed. Any value greater than 0 will cause all currently defined debug output to be printed to stdout. The debuglevel is passed to any new HTTPResponse objects that are created.

バージョン 3.1 で追加.

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

HTTP トンネリング接続のホスト名とポート番号を設定します。これによりプロキシサーバを通しての接続を実行できます。

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.

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.

For example, to tunnel through a HTTPS proxy server running locally on port 8080, we would pass the address of the proxy to the HTTPSConnection constructor, and the address of the host that we eventually want to reach to the set_tunnel() method:

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

バージョン 3.2 で追加.

バージョン 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.

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.

バージョン 3.12 で追加.

HTTPConnection.connect()

Connect to the server specified when the object was created. By default, this is called automatically when making a request if the client does not already have a connection.

Raises an auditing event http.client.connect with arguments self, host, port.

HTTPConnection.close()

サーバへの接続を閉じます。

HTTPConnection.blocksize

Buffer size in bytes for sending a file-like message body.

バージョン 3.7 で追加.

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)

サーバへの接続が確立したら、最初にこのメソッドを呼び出さなくてはなりません。このメソッドは method 文字列、url 文字列、そして HTTP バージョン (HTTP/1.1) からなる一行を送信します。Host:Accept-Encoding: ヘッダの自動送信を無効にしたい場合 (例えば別のコンテンツエンコーディングを受け入れたい場合) には、skip_hostskip_accept_encoding を偽でない値に設定してください。

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

RFC 822 形式のヘッダをサーバに送ります。この処理では、 header 、コロンとスペース、そして最初の引数からなる 1 行をサーバに送ります。追加の引数を指定した場合、継続して各行にタブ一つと引数の入った引数行が送信されます。

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

サーバに空行を送り、ヘッダ部が終了したことを通知します。オプションの message_body 引数を、リクエストに関連したメッセージボディを渡すのに使うことが出来ます。

If encode_chunked is True, the result of each iteration of message_body will be chunk-encoded as specified in RFC 7230, Section 3.3.1. How the data is encoded is dependent on the type of message_body. If message_body implements the buffer interface the encoding will result in a single chunk. If message_body is a collections.abc.Iterable, each iteration of message_body will result in a chunk. If message_body is a file object, each call to .read() will result in a chunk. The method automatically signals the end of the chunk-encoded data immediately after message_body.

注釈

Due to the chunked encoding specification, empty chunks yielded by an iterator body will be ignored by the chunk-encoder. This is to avoid premature termination of the read of the request by the target server due to malformed encoding.

バージョン 3.6 で変更: Added chunked encoding support and the encode_chunked parameter.

HTTPConnection.send(data)

サーバにデータを送ります。このメソッドは endheaders() が呼び出された直後で、かつ getresponse() が呼び出される前に使わなければなりません。

Raises an auditing event http.client.send with arguments self, data.

HTTPResponse オブジェクト

HTTPResponse インスタンスはサーバからのHTTPレスポンスをラップします。これを使用してリクエストヘッダとエンティティボディへアクセスすることができます。レスポンスはイテレート可能なオブジェクトであり、また with文と使うことも可能です。

バージョン 3.5 で変更: The io.BufferedIOBase interface is now implemented and all of its reader operations are supported.

HTTPResponse.read([amt])

応答の本体全体か、amt バイトまで読み出して返します。

HTTPResponse.readinto(b)

バッファ b にレスポンスボディの次のデータを最大 len(b) バイト読み込みます。何バイト読んだかを返します。

バージョン 3.3 で追加.

HTTPResponse.getheader(name, default=None)

Return the value of the header name, or default if there is no header matching name. If there is more than one header with the name name, return all of the values joined by ', '. If default is any iterable other than a single string, its elements are similarly returned joined by commas.

HTTPResponse.getheaders()

(header, value) のタプルからなるリストを返します。

HTTPResponse.fileno()

ソケットの fileno を返します。

HTTPResponse.msg

A http.client.HTTPMessage instance containing the response headers. http.client.HTTPMessage is a subclass of email.message.Message.

HTTPResponse.version

サーバが使用した HTTP プロトコルバージョンです。10 は HTTP/1.0 を、11 は HTTP/1.1 を表します。

HTTPResponse.url

取得されたリソースの URL、主にリダイレクトが発生したかどうかを確認するために利用します。

HTTPResponse.headers

Headers of the response in the form of an email.message.EmailMessage instance.

HTTPResponse.status

サーバから返される状態コードです。

HTTPResponse.reason

サーバから返される応答の理由文です。

HTTPResponse.debuglevel

A debugging hook. If debuglevel is greater than zero, messages will be printed to stdout as the response is read and parsed.

HTTPResponse.closed

ストリームが閉じている場合 True となります。

HTTPResponse.geturl()

バージョン 3.9 で非推奨: 非推奨となったので url を使用してください。

HTTPResponse.info()

バージョン 3.9 で非推奨: 非推奨となったので headers を使用してください。

HTTPResponse.getcode()

バージョン 3.9 で非推奨: 非推奨となったので status を使用してください。

使用例

以下は GET リクエストの送信方法を示した例です:

>>> 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()

次の例のセッションでは、HEAD メソッドを利用しています。HEAD メソッドは全くデータを返さないことに注目してください。

>>> 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

Here is an example session that uses the POST method:

>>> 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()

Client side HTTP PUT requests are very similar to POST requests. The difference lies only on the server side where HTTP servers will allow resources to be created via PUT requests. It should be noted that custom HTTP methods are also handled in urllib.request.Request by setting the appropriate method attribute. Here is an example session that uses the PUT method:

>>> # 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

HTTPMessage オブジェクト

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

http.client.HTTPMessage のインスタンスは HTTP レスポンスヘッダを格納します。 email.message.Message クラスを利用して実装されています。