它没有记录,但看起来您应该可以使用httplib.HTTPConnection.send()
它:
In [13]: httplib.HTTPConnection.send??
Type: instancemethod
String Form:<unbound method HTTPConnection.send>
File: /usr/local/lib/python2.7/httplib.py
Definition: httplib.HTTPConnection.send(self, data)
Source:
def send(self, data):
"""Send `data' to the server."""
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()
if self.debuglevel > 0:
print "send:", repr(data)
blocksize = 8192
if hasattr(data,'read') and not isinstance(data, array):
if self.debuglevel > 0: print "sendIng a read()able"
datablock = data.read(blocksize)
while datablock:
self.sock.sendall(datablock)
datablock = data.read(blocksize)
else:
self.sock.sendall(data)
该request()
方法结合了标头和正文并将其传递给此函数,该函数看起来应该处理字符串或文件对象。
当然,您仍然需要知道主机才能创建HTTPConnection
对象,因此您的代码可能看起来像这样(未经测试):
import httplib
conn = httplib.HTTPConnection('127.0.0.1')
conn.send(open(filename))
response = conn.getresponse()
编辑:事实证明,有一些内部状态的东西使它无法按原样工作,这是一个解决方法(谷歌主页的完整示例),但它有点像黑客。httplib
使用 Python 2.6 和 2.7 进行测试,仅通过替换为3.x 似乎不起作用http.client
:
import httplib
conn = httplib.HTTPConnection('www.google.com')
conn.send('GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n')
conn._HTTPConnection__state = httplib._CS_REQ_SENT
response = conn.getresponse()
这里的关键部分是将conn.__state
(mangled name) 设置为httplib._CS_REQ_SENT
after call send()
。