我正在尝试编写一个python脚本来对Mozenda API执行批量插入。他们在文档中以C#为例。 https://mozenda.com/api#h9
test.xml - 以下示例。
<ItemList>
<Item>
<First>32</First>
<Second>03</Second>
<Third>403</Third>
<Fourth>015</Fourth>
<Fifth>0000</Fifth>
<PIN>32034030150000</PIN>
</Item>
</ItemList>
我的代码:
import urllib2
import urllib
url = 'https://api.mozenda.com/rest?WebServiceKey=[CANNOT-PROVIDE]&Service=Mozenda10&Operation=Collection.AddItem&CollectionID=1037'
fileName = '/Users/me/Desktop/test.xml'
req = urllib2.Request(url, fileName)
moz_response = urllib2.urlopen(req)
response_data = moz_response.read()
print response_data
输出:
<?xml version="1.0" encoding="utf-8"?>
<CollectionAddItemResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Result>Success</Result>
<ItemID>1056</ItemID>
</CollectionAddItemResponse>
输出显示成功,但未按预期插入数据。我怀疑xml需要以某种方式编码,但我不确定......
C#示例位于Mozenda网站下面:
string webServiceKey = C70E1F84-E12B-4e73-B199-2EE6D43AF44E; //Your Account WebServiceKey.
string collectionID = 1001; //The ID of the destination Collection.
string url = string.Format(
"https://api.mozenda.com/rest?WebServiceKey={0}&Service=Mozenda10&Operation=Collection.AddItem&CollectionID={1}",
webServiceKey, collectionID);
string fileName = "C:\\Temp\\NewItems.xml"; //Path to the file containing the items to be uploaded.
WebClient client = new WebClient();
byte[] responseBinary = client.UploadFile(url, fileName);
string response = Encoding.UTF8.GetString(responseBinary);
答案 0 :(得分:2)
您没有正确设置您的请求。当您执行POST请求时,您必须按照RFC 1341, section 7.2.1指定的方式设置请求正文
这是Python中的一个例子
from urllib2 import urlopen, Request
from string import ascii_uppercase, digits
from random import choice
# Open your data file
with open("C:\datafile.xml", "r") as data_file:
data_file_string = data_file.read()
# The URL
url = 'https://api.mozenda.com/rest?WebServiceKey=[CANNOT-PROVIDE]&Service=Mozenda10&Operation=Collection.AddItem&CollectionID=1037'
# The boundary delimits where the file to be uploaded starts and where it ends.
boundary = "".join(choice(ascii_uppercase + digits)
for x in range(20))
body_list = []
body_list.append("--" + boundary)
body_list.append("Content-Disposition: form-data;"
" name='file'; filename=''")
body_list.append("Content-Type: application/octet-stream")
body_list.append("")
body_list.append(data_file_string)
body_list.append("--{0}--".format(boundary))
body_list.append("")
body="\r\n".join(body_list).encode("utf8")
content_type = ("multipart/form-data; boundary="
"{0}").format(boundary)
headers = {"Content-Type": content_type,
"Content-Length": str(len(body))} # Tells how big the content is
request = Request(url, body, headers)
result = urlopen(url=request).read()