Python调用POST接口传递JSON文件遇400/415错误求助
问题分析与解决方案
看起来你遇到的核心问题是请求格式与接口期望不匹配,导致了400/415错误。我们先拆解下问题根源,再给出针对性的修复方案:
为什么会报错?
你的代码里用了files参数发送请求,这本质是在模拟multipart/form-data格式的文件上传,但结合你的错误表现,接口大概率是期望直接接收application/json格式的请求体(就像Postman里选raw -> JSON的方式),两者的请求格式完全不同:
- 当你手动添加
Content-type: application/json时,requests库会因为你用了files参数,自动把请求的Content-Type改成multipart/form-data,导致请求头和实际内容格式冲突,服务器返回400; - 当你移除headers时,请求格式是
multipart/form-data,但接口只接受application/json,所以返回415(不支持的媒体类型)。
解决方案分两种情况
情况1:接口期望直接接收JSON请求体(Postman用raw JSON调用)
这种情况下不需要用files参数,直接读取JSON文件内容作为请求体发送即可:
import os import json import requests from requests.auth import HTTPBasicAuth config_directory = 'my-laptp-location\\where-i-have\\all-mt-files' url = 'http://localhost:8080/api/v1/update' usr = 'user' passwd = 'pass' # 用json参数的话,requests会自动设置Content-Type为application/json,headers可以简化 headers = {'Accept': 'application/json'} for fileName in os.listdir(config_directory): print('Processing file: ', fileName) abs_path = os.path.abspath(os.path.join(config_directory, fileName)) with open(abs_path, 'r', encoding='utf-8') as f: # 读取文件并解析为JSON对象 json_payload = json.load(f) # 用json参数发送请求,自动处理序列化和Content-Type r = requests.post(url, json=json_payload, auth=HTTPBasicAuth(usr, passwd), headers=headers) print(f"状态码: {r.status_code}") # 打印响应内容,方便看服务器返回的具体错误信息 print(f"响应内容: {r.text}")
情况2:接口确实期望接收文件上传(Postman用form-data上传文件)
如果你的Postman是通过form-data字段上传JSON文件(比如key设为file),那需要修正files参数的格式,且不要手动设置Content-Type(requests会自动处理multipart格式的头):
import os import requests from requests.auth import HTTPBasicAuth config_directory = 'my-laptp-location\\where-i-have\\all-mt-files' url = 'http://localhost:8080/api/v1/update' usr = 'user' passwd = 'pass' for fileName in os.listdir(config_directory): print('Processing file: ', fileName) abs_path = os.path.abspath(os.path.join(config_directory, fileName)) # files的格式是 {'接口要求的字段名': (文件名, 文件对象, 文件MIME类型)} # 注意这里的字段名要和Postman里的key一致,比如Postman用的是'file',就写'file' with open(abs_path, 'rb') as f: files = {'file': (fileName, f, 'application/json')} r = requests.post(url, files=files, auth=HTTPBasicAuth(usr, passwd)) print(f"状态码: {r.status_code}") print(f"响应内容: {r.text}")
额外排查建议
- 先确认Postman的具体调用方式:是用
raw JSON还是form-data上传文件,这决定了用哪种方案; - 打印响应的
r.text内容,服务器通常会返回具体的错误原因(比如“缺少某个字段”“格式不支持”),能帮你更快定位问题。
内容的提问来源于stack exchange,提问作者Indrajeet Gour
相关产品推荐
相关产品推荐

