如何在 urllib2 请求中获得默认标头? [英] How do you get default headers in a urllib2 Request?

查看:20
本文介绍了如何在 urllib2 请求中获得默认标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 urllib2 的 Python 网络客户端.将 HTTP 标头添加到我的传出请求中很容易.我只是创建了一个我想添加的头的字典,并将它传递给请求初始值设定项.

I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.

但是,其他标准"HTTP 标头会添加到请求中,以及我明确添加的自定义标头.当我使用 Wireshark 嗅探请求时,除了我自己添加的标头之外,我还会看到标头.我的问题是如何访问这些标题?我想记录每个请求(包括 完整 组 HTTP 标头),但不知道如何.

However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the full set of HTTP headers), and can't figure out how.

有什么指点吗?

简而言之:如何从 urllib2 创建的 HTTP 请求中获取所有传出标头?

in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?

推荐答案

如果您想查看发送出去的文字 HTTP 请求,并因此查看与线路上所表示的完全一样的每个最后一个标头,那么您可以告诉urllib2 使用您自己的 HTTPHandler 版本,打印出(或保存,或其他)传出的 HTTP 请求.

If you want to see the literal HTTP request that is sent out, and therefore see every last header exactly as it is represented on the wire, then you can tell urllib2 to use your own version of an HTTPHandler that prints out (or saves, or whatever) the outgoing HTTP request.

import httplib, urllib2

class MyHTTPConnection(httplib.HTTPConnection):
    def send(self, s):
        print s  # or save them, or whatever!
        httplib.HTTPConnection.send(self, s)

class MyHTTPHandler(urllib2.HTTPHandler):
    def http_open(self, req):
        return self.do_open(MyHTTPConnection, req)

opener = urllib2.build_opener(MyHTTPHandler)
response = opener.open('http://www.google.com/')

运行这段代码的结果是:

The result of running this code is:

GET / HTTP/1.1
Accept-Encoding: identity
Host: www.google.com
Connection: close
User-Agent: Python-urllib/2.6

这篇关于如何在 urllib2 请求中获得默认标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆