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

hou*_*uqp 6 python urllib2

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

Mar*_*agh 5

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()
Run Code Online (Sandbox Code Playgroud)

访问日志

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"
Run Code Online (Sandbox Code Playgroud)


jfs*_*jfs 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])
Run Code Online (Sandbox Code Playgroud)