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

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

======================================================================

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

参考: より高水準の HTTP クライアントインターフェースとして Requests パッケ
    ージ が推奨されています。

注釈:

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

Availability: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは
、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_address*、*context* そして
   *check_hostname* が追加されました。

   バージョン 3.2 で変更: このクラスは現在、可能であれば (つまり
   "ssl.HAS_SNI" が真の場合) HTTPS のバーチャルホストをサポートしてい
   ます。

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

   バージョン 3.4.3 で変更: このクラスは今や全ての必要な証明書とホスト
   名の検証をデフォルトで行うようになりました。 *context* パラメーター
   に "ssl._create_unverified_context()" を渡すことで、昔の、検証を行
   わない振る舞いに戻すことができます。

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

   Added in version 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.

   注釈:

     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.

   バージョン 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.Note that this does not apply to "OSError"s
   raised by the underlying socket. Instead the caller is responsible
   to call "close()" on the existing connection.

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.

   Added in version 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")

   Added in version 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".

   Added in version 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.

   Added in version 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_host* や
   *skip_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) バイト読み
   込みます。何バイト読んだかを返します。

   Added in version 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" クラスを利用して実装されています。
