如何将JSON作为多部分POST请求

时间:2016-03-11 12:00:58

标签: python json http-post python-requests multipartform-data

我有以下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.

请指出我的错误。我应该改变什么才能使它发挥作用?

2 个答案:

答案 0 :(得分:10)

您自己设置标题,包括边界。不要这样做; requests为您生成边界并将其设置在标头中,但如果设置标头,则生成的有效负载和标头将不匹配。只需完全删除标题:

def send_request():
    payload = {"param_1": "value_1", "param_2": "value_2"}
    files = {
         'json': (None, json.dumps(payload), 'application/json'),
         'file': (os.path.basename(file), open(file, 'rb'), 'application/octet-stream')
    }

    r = requests.post(url, files=files)
    print(r.content)

请注意,我还为file部分提供了一个文件名(file路径`的基本名称)。

有关多部分POST请求的详细信息,请参阅advanced section of the documentation

答案 1 :(得分:0)

如果有人搜索准备使用的方法来将python字典转换为多部分形式的数据结构,here是进行这种转换的简单示例:

{"some": ["balls", "toys"], "field": "value", "nested": {"objects": "here"}}
    ->
{"some[0]": "balls", "some[1]": "toys", "field": "value", "nested[objects]": "here"}

要发送一些数据,您可能需要像这样使用multipartify方法:

import requests  # library for making requests

payload = {
    "person": {"name": "John", "age": "31"},
    "pets": ["Dog", "Parrot"],
    "special_mark": 42,
}  # Example payload

requests.post("https://example.com/", files=multipartify(payload))

要与任何文件一起发送相同的数据(如OP所希望的那样),您可以像这样简单地添加它:

converted_data = multipartify(payload)
converted_data["attachment[0]"] = ("file.png", b'binary-file', "image/png")

requests.post("https://example.com/", files=converted_data)

请注意,attachment是服务器端点定义的名称,可能会有所不同。另外,attachment[0]表示它是您请求中的第一个文件-这也应由API文档定义。