在Python中,getresponse()返回什么?

TIM*_*MEX 11 python unix linux http

 import httplib
    conn = httplib.HTTPConnection(head)
    conn.request("HEAD",tail)
    res = conn.getresponse()
Run Code Online (Sandbox Code Playgroud)

我可以得到res.status,这是http状态代码.

我还能得到什么其他元素?为什么当我打印res时,它不会打印字典?我只是想看看那本词典中的键......

Ste*_*202 23

您始终可以使用检查对象dir; 这将显示它具有哪些属性.

>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.nl")
>>> 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']
Run Code Online (Sandbox Code Playgroud)

同样,help如果对象的文档具有__doc__属性,则可以调用它来显示对象的文档.正如您所看到的,情况就是如此res,请尝试:

>>> help(res)
Run Code Online (Sandbox Code Playgroud)

除此之外,文档声明getresponse返回一个HTTPResponse对象.因此,正如您可以在那里阅读(和help(res)),在HTTPResponse对象上定义了以下属性和方法:

  • HTTPResponse.read([amt]):读取并返回响应正文,或者直到下一个amt字节.

  • HTTPResponse.getheader(name[, default]):获取标题名称的内容,如果没有匹配的标题,则为默认值.

  • HTTPResponse.getheaders():返回(标题,值)元组的列表. (版本2.4中的新功能.)

  • HTTPResponse.msg:包含响应标头的mimetools.Message实例.

  • HTTPResponse.version:服务器使用的HTTP协议版本.10表示HTTP/1.0,11表示HTTP/1.1.

  • HTTPResponse.status:服务器返回的状态代码.

  • HTTPResponse.reason:服务器返回的原因短语.