@@ -221,8 +221,9 @@ def _read_headers(fp):
221221 break
222222 return headers
223223
224- def parse_headers (fp , _class = HTTPMessage ):
225- """Parses only RFC2822 headers from a file pointer.
224+ def _parse_header_lines (header_lines , _class = HTTPMessage ):
225+ """
226+ Parses only RFC2822 headers from header lines.
226227
227228 email Parser wants to see strings rather than bytes.
228229 But a TextIOWrapper around self.rfile would buffer too many bytes
@@ -231,10 +232,15 @@ def parse_headers(fp, _class=HTTPMessage):
231232 to parse.
232233
233234 """
234- headers = _read_headers (fp )
235- hstring = b'' .join (headers ).decode ('iso-8859-1' )
235+ hstring = b'' .join (header_lines ).decode ('iso-8859-1' )
236236 return email .parser .Parser (_class = _class ).parsestr (hstring )
237237
238+ def parse_headers (fp , _class = HTTPMessage ):
239+ """Parses only RFC2822 headers from a file pointer."""
240+
241+ headers = _read_headers (fp )
242+ return _parse_header_lines (headers , _class )
243+
238244
239245class HTTPResponse (io .BufferedIOBase ):
240246
@@ -858,7 +864,7 @@ def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
858864 self ._tunnel_host = None
859865 self ._tunnel_port = None
860866 self ._tunnel_headers = {}
861- self ._proxy_response_headers = None
867+ self ._raw_proxy_headers = None
862868
863869 (self .host , self .port ) = self ._get_hostport (host , port )
864870
@@ -945,11 +951,11 @@ def _tunnel(self):
945951 try :
946952 (version , code , message ) = response ._read_status ()
947953
948- self ._proxy_response_headers = parse_headers (response .fp )
954+ self ._raw_proxy_headers = _read_headers (response .fp )
949955
950956 if self .debuglevel > 0 :
951- for hdr , val in self ._proxy_response_headers . items () :
952- print (" header:" , hdr + ":" , val )
957+ for header in self ._raw_proxy_headers :
958+ print (' header:' , header . decode () )
953959
954960 if code != http .HTTPStatus .OK :
955961 self .close ()
@@ -958,6 +964,21 @@ def _tunnel(self):
958964 finally :
959965 response .close ()
960966
967+ def get_proxy_response_headers (self ):
968+ """
969+ Returns a dictionary with the headers of the response
970+ received from the proxy server to the CONNECT request
971+ sent to set the tunnel.
972+
973+ If the CONNECT request was not sent, the method returns
974+ an empty dictionary.
975+ """
976+ return (
977+ _parse_header_lines (self ._raw_proxy_headers )
978+ if self ._raw_proxy_headers is not None
979+ else {}
980+ )
981+
961982 def connect (self ):
962983 """Connect to the host and port specified in __init__."""
963984 sys .audit ("http.client.connect" , self , self .host , self .port )
0 commit comments