如果您需要访问所用套接字上的此类低级属性,则必须重载一些对象。
首先,您需要创建HTTPHandler的子类,在标准库中执行以下操作:
class HTTPHandler(AbstractHTTPHandler):
def http_open(self, req):
return self.do_open(httplib.HTTPConnection, req)
http_request = AbstractHTTPHandler.do_request_
如您所见,它使用一个HTTPConnection
打开连接...您也必须覆盖它;)以升级该connect()
方法。
这样的事情应该是一个好的开始:
class LowLevelHTTPConnection(httplib.HTTPConnection):
def connect(self):
httplib.HTTPConnection.connect(self)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
class LowLevelHTTPHandler(HTTPHandler):
def http_open(self, req):
return self.do_open(LowLevelHTTPConnection, req)
urllib2 足够聪明,可以让你继承一些处理程序然后使用它,urllib2.build_opener就是为此而设计的:
urllib2.install_opener(urllib2.build_opener(LowLevelHTTPHandler)) # tell urllib2 to use your HTTPHandler in replacement of the standard HTTPHandler
httpRequest = urllib2.Request("http:/www....com")
pageContent = urllib2.urlopen(httpRequest)
pageContent.readline()