如何通过urllib2发送HTTP / 1.0请求?

时间:2012-12-01 05:38:25

标签: python urllib2

似乎urllib2默认发送HTTP / 1.1请求?

2 个答案:

答案 0 :(得分:5)

为避免猴子修补httplib(全局更​​改),您可以继承HTTPConnection并定义自己的http处理程序:

#!/usr/bin/env python
try:
    from httplib import HTTPConnection
    from urllib2 import HTTPHandler, build_opener
except ImportError: # Python 3
    from http.client import HTTPConnection
    from urllib.request import HTTPHandler, build_opener

class HTTP10Connection(HTTPConnection):
    _http_vsn = 10
    _http_vsn_str = "HTTP/1.0" 

class HTTP10Handler(HTTPHandler):
    def http_open(self, req):
        return self.do_open(HTTP10Connection, req)

opener = build_opener(HTTP10Handler)
print(opener.open('http://stackoverflow.com/q/13656757').read()[:100])

答案 1 :(得分:4)

urllib2使用引擎盖下的httplib来建立连接。您可以将其更改为http 1.0,如下所示。我已经包含了我的apache服务器访问日志,以显示http连接如何更改为1.0

<强>码

import urllib2, httplib
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'
print urllib2.urlopen('http://localhost/').read()

<强>的access.log

127.0.0.1 - - [01/Dec/2012:09:10:27 +0300] "GET / HTTP/1.1" 200 454 "-" "Python-urllib/2.7"
127.0.0.1 - - [01/Dec/2012:09:16:32 +0300] "GET / HTTP/1.0" 200 454 "-" "Python-urllib/2.7"