开发者

Get headers sent in urllib2 http request

I know how to get the headers RECEIVED

resp = urllib2.urlopen('http://www.google.com')
print resp.info()

But how do you access the headers SENT to 'http:开发者_C百科//www.google.com' ?

I usually use wireshark to analyze and see what is actually being sent, but I'd like to have access to this information in my script.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜