Python – In Python, what does getresponse() return

By | October 13, 2023

 import httplib
    conn = httplib.HTTPConnection(head)
    res = conn.getresponse()

I can get the res.status , which is the http status code.

What other elements can I get?
Why is it that when I do print res, it won’t print the dictionary? I just want to see the keys that are in that dictionary…

Best Solution

You can always inspect an object using dir; that will show you which attributes it has.

>>> import httplib
>>> conn = httplib.HTTPConnection("")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> dir(res)
['__doc__', '__init__', '__module__', '_check_close', '_method', '_read_chunked', '_read_status', '_safe_read', 'begin', 'chunk_left', 'chunked', 'close', 'debuglevel', 'fp', 'getheader', 'getheaders', 'isclosed', 'length', 'msg', 'read', 'reason', 'status', 'strict', 'version', 'will_close']

Likewise, you can invoke help, which will show an object’s documentation, if it has a __doc__ attribute. As you can see, this is the case for res, so try:

>>> help(res)

Other than that, the documentation states that getresponse returns an HTTPResponse object. Thus, as you can read there (and in help(res)), the following properties and methods are defined on HTTPResponse objects:

    Reads and returns the response body, or up to the next amt bytes.

  • HTTPResponse.getheader(name[, default]):
    Get the contents of the header name, or default if there is no matching header.

  • HTTPResponse.getheaders():
    Return a list of (header, value) tuples.
    (New in version 2.4.)

  • HTTPResponse.msg:
    A mimetools.Message instance containing the response headers.

  • HTTPResponse.version:
    HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.

  • HTTPResponse.status:
    Status code returned by server.

  • HTTPResponse.reason:
    Reason phrase returned by server.

Category: Uncategorized