Python 获取在urllib2 http请求中发送的标头
我知道如何收到邮件头Python 获取在urllib2 http请求中发送的标头,python,Python,我知道如何收到邮件头 resp = urllib2.urlopen('http://www.google.com') print resp.info() 但是,如何访问发送到的标题http://www.google.com”“是吗 我通常使用wireshark分析并查看实际发送的内容,但我希望能够在脚本中访问这些信息。有关如何检查实际请求的信息,请参见此处:如何访问类外的相同标头?除了打印出来之外,我还需要对标题做些什么。不幸的是,没有使用globals是很难做到的,因为opener.open
resp = urllib2.urlopen('http://www.google.com')
print resp.info()
但是,如何访问发送到的标题http://www.google.com”“是吗
我通常使用wireshark分析并查看实际发送的内容,但我希望能够在脚本中访问这些信息。有关如何检查实际请求的信息,请参见此处:如何访问类外的相同标头?除了打印出来之外,我还需要对标题做些什么。不幸的是,没有使用globals是很难做到的,因为opener.open会返回一个由HTTPResponse的HTTPMessage创建的AddInfo URL(这可能对您毫无意义)无论如何,您可以将标题附加到响应中,并可能以req作为前缀。我正在添加代码作为另一个答案,或者有一种方法可以在注释中格式化?
import httplib
import urllib2
class CustomHTTPConnection(httplib.HTTPConnection):
def request(self, method, url, body=None, headers={}):
print headers
self._send_request(method, url, body, headers)
class CustomHTTPHandler(urllib2.AbstractHTTPHandler):
def http_open(self, req):
return self.do_open(CustomHTTPConnection, req)
http_request = urllib2.AbstractHTTPHandler.do_request_
if __name__ == '__main__':
opener = urllib2.OpenerDirector()
opener.add_handler(CustomHTTPHandler())
res = opener.open('http://www.google.it/')
import httplib
import urllib2
class CustomHTTPConnection(httplib.HTTPConnection):
def request(self, method, url, body=None, headers={}):
self.req_headers = headers
self._send_request(method, url, body, headers)
def getresponse(self, buffering=False):
resp = httplib.HTTPConnection.getresponse(self, buffering)
for key, value in self.req_headers.items():
resp.msg.headers.append('req_%s: %s\r\n' % (key, value))
return resp
class CustomHTTPHandler(urllib2.AbstractHTTPHandler):
def http_open(self, req):
resp = self.do_open(CustomHTTPConnection, req)
return resp
http_request = urllib2.AbstractHTTPHandler.do_request_
if __name__ == '__main__':
opener = urllib2.OpenerDirector()
opener.add_handler(CustomHTTPHandler())
res = opener.open('http://www.google.it/')
info = res.info()
print info