【发布时间】:2016-06-26 16:06:29
【问题描述】:
我有以下 POST 请求表(简化版):
POST /target_page HTTP/1.1
Host: server_IP:8080
Content-Type: multipart/form-data; boundary=AaaBbbCcc
--AaaBbbCcc
Content-Disposition: form-data; name="json"
Content-Type: application/json
{ "param_1": "value_1", "param_2": "value_2"}
--AaaBbbCcc
Content-Disposition: form-data; name="file"; filename="..."
Content-Type: application/octet-stream
<..file data..>
--AaaBbbCcc--
我尝试使用 requests 发送 POST 请求:
import requests
import json
file = "C:\\Path\\To\\File\\file.zip"
url = 'http://server_IP:8080/target_page'
def send_request():
headers = {'Content-type': 'multipart/form-data; boundary=AaaBbbCcc'}
payload = { "param_1": "value_1", "param_2": "value_2"}
r = requests.post(url, files={'json': (None, json.dumps(payload), 'application/json'), 'file': (open(file, 'rb'), 'application/octet-stream')}, headers=headers)
print(r.content)
if __name__ == '__main__':
send_request()
但它返回状态 400 并带有以下注释:
Required request part \'json\' is not present.
The request sent by the client was syntactically incorrect.
请指出我的错误。我应该改变什么才能让它工作?
【问题讨论】:
-
您需要注明
Content-Type: application/json -
@noctilux:不适合你不知道的多部分帖子。
-
不要不自己设置
Content-type标头,留给requests生成。 -
在stackoverflow.com/questions/19439961/…中据说不将json部分编码为json作为一种解决方法
-
如果你没有固定在 pyrequests 上,你可以使用 libcurl 和 PycURL (pycurl.io/docs/latest)。在他的线程中是一个在 cURL 中使用 json 的多部分 POST 的工作示例:stackoverflow.com/questions/29231926/…
标签: python json http-post python-requests multipartform-data