我正在尝试调试为什么我无法将带有请求.post()
的xml文件发布到API。以下wget
命令可以正常工作:
wget -vv --no-check-certificate --post-file dynobjadd.xml \
"https://1.1.1.1/api/?type=user-id&action=set&key=$MYSUPERSECRETKEY=&file-name=dynobjadd.xml&client=wget" \
--no-http-keep-alive -O response.out
成功的wget输出:
...
URI encoding = ‘UTF-8’
--2017-01-05 13:21:11-- https://1.1.1.1/api/?type=user-id&action=set&key=$MYSUPERSECRETKEY=&file-name=dynobjadd.xml&client=wget
Certificates loaded: 165
Connecting to 1.1.1.1:443... connected.
...
---request begin---
POST https://1.1.1.1/api/?type=user-id&action=set&key=$MYSUPERSECRETKEY=&file-name=dynobjadd.xml&client=wget HTTP/1.1
User-Agent: Wget/1.18 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: 1.1.1.1
Connection: Close
Content-Type: application/x-www-form-urlencoded
Content-Length: 175
---request end---
[writing BODY file dynobjadd.xml ... done]
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 200 OK
Server:
Date: Thu, 05 Jan 2017 20:21:12 GMT
Content-Type: application/xml; charset=UTF-8
Content-Length: 255
Connection: close
ETag: "437cf-12b-56e39c36"
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Thu, 19 Nov 1981 08:52:00 GMT
X-FRAME-OPTIONS: SAMEORIGIN
Set-Cookie: PHPSESSID=123123; path=/; secure; HttpOnly
---response end---
200 OK
我正在尝试的python代码:
xml = open('dynobjadd.xml').read()
url = 'https://1.1.1.1/api/?type=user-id&action=set&key=$MYSUPERSECRETKEY=&file-name=dynobjadd.xml&client=requests'
r = requests.post(url, data=xml, verify=False )
r.content()
输出:
<response status = 'error' code = '400'><result><msg>No file uploaded</msg></result></response>
答案 0 :(得分:2)
您应该使用参数&#39;文件&#39;。 来自http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}