总结可行方案:
1.http.request传的参数中带fields时,带上特定的boundary(以WebKitFormBoundary开头的, 原因未知, 知道的朋友可以留言告知),headers中不要带Content-Type;
2.http.request传的参数要带上headers的话,格式应该是:Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
最终的代码修改:
urllib3.disable_warnings()
http = urllib3.PoolManager()
with open('example.jpeg','rb') as fp:
POST请求四种传递正文的方式
(1)请求正文是application/x-www-form-urlencoded
最常见的POST提交数据的方式,浏览器的原生form表单,如果不设置enctype属性,那么最终就会以application/x-www-form-urlencoded方式提交数据。
(2)multipart/form-data
上传文件的表单
(3)application/json
用来告诉服务器消息主体是序列化之后的JSON字符串。
(4)text/xml
它是一种使用HTTP作为传输协议,XML作为编码方式的远程调用规范。
urllib3.disable_warnings()
http = urllib3.PoolManager()
file_data = fp.read()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
#方案1
r = http.request(
'POST',
'http://httpbin.org/post',
headers = {},
multipart_boundary = boundary,
fields={
'text': ('None', "upload a string",'None'),
'file': ('example.jpeg',file_data,"image/jpeg"),
})
#方案2
r = http.request(
'POST',
'http://httpbin.org/post',
headers = {'Content-Type':"multipart/form-data;%s"%boundary},
multipart_boundary = boundary,
fields={
'text': ('None', "upload a string",'None'),
'file': ('example.jpeg',file_data,"image/jpeg"),
})
————————————————