python - 如何在 Python 中打印出 http-response header

标签 python http header response

今天我实际上需要从 http-header 响应中检索数据。但是因为我以前从未做过,而且你在谷歌上也找不到太多关于这个的东西。我决定在这里问我的问题。

实际问题是:如何在 python 中打印 http-header 响应数据?我在 Python3.5 中使用 requests 模块工作,但尚未找到执行此操作的方法。

最佳答案

更新:根据 OP 的评论,仅需要响应 header 。在请求模块的以下文档中写得更简单:

We can view the server's response headers using a Python dictionary:

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

尤其是文档注释:

The dictionary is special, though: it's made just for HTTP headers. According to RFC 7230, HTTP Header names are case-insensitive.

So, we can access the headers using any capitalization we want:

并继续解释有关 RFC 合规性的更多聪明之处。

Requests documentation状态:

Using Response.iter_content will handle a lot of what you would otherwise have to handle when using Response.raw directly. When streaming a download, the above is the preferred and recommended way to retrieve the content.

它提供了示例:

>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

但也提供了如何通过重定向到文件等并使用不同的方法在实践中做到这一点的建议:

Using Response.iter_content will handle a lot of what you would otherwise have to handle when using Response.raw directly

关于python - 如何在 Python 中打印出 http-response header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616460/

相关文章:

python - super() 在 Sublime Text 中抛出错误,在 PyCharm/Terminal 中有效

python - 如何在 Python 中查询和管理 Debian 包存储库?

用于在 CURLOPT_URL 中传递变量的 php pb

Apache 2 : Environment variables for user http

html - 页面顶部的页眉间隙

python - 从 Perl 调用 Python 模块

python - Pandas 和 Scikit : memory usage when slicing DataFrame

javascript - 如何处理纯文本服务器响应?

header - 如何将 Blogger 标题拆分为 2 列?

php - 似乎无法同时发送 404 和 Location header