且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用python请求将XML文件发送到Rest API

更新时间:2022-11-27 19:58:45

您的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))