HTTPConnection.request() documentation说:
如果存在body参数,则它应该是标题完成后要发送的数据字符串。或者,它可以是一个打开的文件对象,在这种情况下发送文件的内容;这个文件对象应该支持fileno()和read()方法。
所以这通常有效:
import httplib
import os
f = open('data.dat', 'rb')
conn = httplib.HTTPSConnection('localhost', 8000)
conn.request("PUT", "/", f, {
"Content-Length": os.fstat(f.fileno()).st_size,
"Content-Type": "application/octet-stream",
})
但如果data.dat
大于~5.5MB,则停止工作:
Traceback (most recent call last):
File "script.py", line 81, in <module>
conn.request("PUT", "/", f, {
File "C:\Python27\lib\httplib.py", line 1057, in request
self._send_request(method, url, body, headers)
File "C:\Python27\lib\httplib.py", line 1097, in _send_request
self.endheaders(body)
File "C:\Python27\lib\httplib.py", line 1053, in endheaders
self._send_output(message_body)
File "C:\Python27\lib\httplib.py", line 901, in _send_output
self.send(message_body)
File "C:\Python27\lib\httplib.py", line 870, in send
self.sock.sendall(datablock)
File "C:\Python27\lib\ssl.py", line 743, in sendall
v = self.send(data[count:])
File "C:\Python27\lib\ssl.py", line 709, in send
v = self._sslobj.write(data)
socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host
但是如果参数f
被f.read()
替换,它会继续工作!