使用python请求将XML文件发送到Rest API [英] send an XML file to rest API using python requests
问题描述
我正在尝试使用rest api POST发送XML文件. api获取xml并创建一个新的实体.
I am trying to send an XML file with a rest api POST. the api takes the xml and creates a new entitiy.
我正在尝试打开文件,然后通过请求将其发送.
I am trying to open the file and then sending it through requests.
filename = 'test.xml'
response = requests.post(api_url, data=json.dumps(open(filename).readlines()))
但是得到了503(API无法获得正确的输入).我的意图是将此XML发送到api.
But getting the 503 (API not able to get the right input). My intention is to send this XML as it is to api.
如果我不执行json.dumps,则会得到ValueError: too many values to unpack
If I don't do json.dumps, I get ValueError: too many values to unpack
推荐答案
您的API使用XML,而不是JSON.当您说data = json.dumps(...)
时,您正在将JSON传递到您的API.这是您收到第一条错误消息的原因-503(API无法获得正确的输入).
Your API takes XML, not JSON. When you say, data = json.dumps(...)
, you are passing JSON to your API. This is the reason for your first error message -- 503 (API not able to get the right input).
requests.post()
将以字典,字符串或类似文件的对象作为其data=
参数.当您执行data = foo.readlines()
时,您要传入一个列表(既不是字符串也不是字典.这就是第二条错误消息的原因-"ValueError:太多的值无法解压缩".
requests.post()
takes ether a dictionary, a string, or a file-like object as its data=
parameter. When you do data = foo.readlines()
, you are passing in a list (which is neither a string nor a dictionary. This is the reason for your second error message -- "ValueError: too many values to unpack".
在不知道您的API的情况下,很难猜测出什么是正确的.话虽如此,试试这个:
Without knowing your API, it is hard to guess what is correct. Having said that, try this:
filename = 'test.xml'
response = requests.post(api_url, data=open(filename).read())
或几乎等同于此:
filename = 'test.xml'
response = requests.post(api_url, data=open(filename))
这篇关于使用python请求将XML文件发送到Rest API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!