如何将JSON作为多部分POST请求的一部分发送 [英] How to send JSON as part of multipart POST-request

查看:424
本文介绍了如何将JSON作为多部分POST请求的一部分发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下POST请求表格(简化):

I have following POST-request form (simplified):

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--

我尝试用<$ c $发送POST请求c>请求:

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 ,并附有以下评论:

but it returns status 400 with following comment:

Required request part \'json\' is not present.
The request sent by the client was syntactically incorrect.

请指出我的错误。我应该更改什么才能使其正常工作?

Please point on my mistake. What should I change to make it work?

推荐答案

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

You are setting the header yourself, including a boundary. Don't do this; requests generates a boundary for you and sets it in the header, but if you already set the header then the resulting payload and the header will not match. Just drop you headers altogether:

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)

请注意,我还给了文件部分文件名(文件的基本名称路径`)。

Note that I also gave the file part a filename (the base name of the file path`).

有关多部分POST请求的详细信息,请参阅高级文档部分

For more information on multi-part POST requests, see the advanced section of the documentation.

这篇关于如何将JSON作为多部分POST请求的一部分发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆