这是我在 python 中需要的 post 请求的目标:
我得到了 XML 文件、url 和身份验证 token 。根据 xml 文件,我从服务器返回 xml 响应。
req = requests.post(url='http://abc123.com/index.php/plan/', \
headers={'auth-token': 'abCdeFgh'}, \
data={'data': open('sample_plan.xml', 'rb')})
发布请求状态代码为 200,但 xml 响应中存在错误,如“<error>invalid XML for request</error>
”。据说在我的发布请求中 xml 文件填写了错误的参数。
但是在另一个工具中 - Postman - https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en ?它可以正常工作并成功获得正确的 xml 响应。我在 Postman 中拥有的内容:
在标题中: Key:Auth-token Value:abCdeFgh
在正文中: 选择了表单数据选项.. Key:数据 Value:选择的 sample_plan.xml 文件..
Goal for parameters (all parameters are mandatory) of post request: 1. in header - Authentication-Token 2. in body - XML file with name/contentID = data
post请求的文件应该放到哪个参数?我已经尝试了几乎所有的东西——基于 python-requests 文档...
感谢您的帮助!
最佳答案
经过几个小时的尝试,我终于明白了!
正确的参数是文件,并且必须有“数据”键和具有 3 个参数的元组值。否则它不能正常工作......
根据请求文档,我使用 files 参数进行分段编码上传 http://docs.python-requests.org/en/master/api/ 使用 key 'data' 我被 + 三元组的值 ('filename', fileobj, 'content_type')
因此,我的问题的答案是(也使用“with”关键字,以便文件在其套件完成后正确关闭)
with open('sample_plan.xml', 'rb') as payload:
headers = {'auth-token': 'abCdeFgh'}
files = {'data': ('sample_plan.xml', payload, 'text/xml')}
req = requests.post(url='http://abc123.com/index.php/plan/', \
headers=headers, files=files)
关于python - POST 请求文件 python-requests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45980396/