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

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

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

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

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

注釈:

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

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

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, key_file=None, cert_file=None[, timeout], source_address=None, *, context=None, check_hostname=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.6 で非推奨: *key_file* および *cert_file* は非推奨とな
   ったので、 *context* を使ってください。 代わりに
   "ssl.SSLContext.load_cert_chain()" を使うか、または
   "ssl.create_default_context()" にシステムが信頼する CA 証明書を選ん
   でもらうかしてください。The *check_hostname* parameter is also
   deprecated; the "ssl.SSLContext.check_hostname" attribute of
   *context* should be used instead.

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)

   このメソッドは、HTTP 要求メソッド *method* およびセレクタ *url* を
   使って、要求をサーバに送ります。

   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.

   *headers* 引数は要求と同時に送信される拡張 HTTP ヘッダの内容からな
   るマップ型でなくてはなりません。

   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.

   注釈:

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

   ヘッダのパラメータは CONNECT リクエストで送信するために他の HTTP ヘ
   ッダにマッピングされます。

   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 で追加.

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.

HTTPConnection.close()

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

HTTPConnection.blocksize

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

   バージョン 3.7 で追加.

上で説明した "request()" メソッドを使うかわりに、以下の4つの関数を使用
して要求をステップバイステップで送信することもできます。

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 で追加: Chunked encoding support.  The
   *encode_chunked* parameter was added.

HTTPConnection.send(data)

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


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

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

以下は "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="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
   >>> conn.close()

Client side "HTTP PUT" requests are very similar to "POST" requests.
The difference lies only the server side where HTTP server will allow
resources to be created via "PUT" request. 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 shows how to send a "PUT" request using http.client:

   >>> # This creates an HTTP message
   >>> # 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 オブジェクト
========================

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