How to send JSON as part of multipart POST-request

后端 未结 2 1979
囚心锁ツ
囚心锁ツ 2020-12-01 22:06

I have following POST-request form (simplified):

POST /target_page HTTP/1.1  
Host: server_IP:8080
Content-Type: multipart/form-data; boundary=AaaBbbCcc

--A         


        
2条回答
  •  半阙折子戏
    2020-12-01 23:02

    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`).

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

提交回复
热议问题