我需要创建访问XML服务的请求,它应该通过HTTP处理。 Ass在文档中说我必须发送" 4相关参数,这些参数将用作标识并将提供请求"。这些参数应该看起来像字符串:
"codes=12345"
"user=user12345"
"password=pass12345"
"partner=part12345"
根据文档,我有两个系统用于发送请求的XML文件:
1通过MIME格式application / x-www-form-编码的URL urlencoded:URL(“urlfile”)
2直接在变量中输入数据,以MIME格式编码 application / x-www-form-urlencoded:直接在变量(“xml”)中。
据我所知,我的请求数据如下:
data='
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE petition SYSTEM "http://xml.example.com/xml/dtd/xml.dtd">
<petition>
<number>Country request</number>
<partner>Company</partner>
<type>5</type>
</petition>'
我使用python库urllib2创建此请求。所以这是我的代码:
request = urllib2.Request(url, data)
request.add_header("codes=12345", "user=user12345", "password=pass12345", "partner=part12345")
但我收到了一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add_header() takes exactly 3 arguments (5 given)
所以我改变了这个标题:
header = {'codes':'12345','user':'user12345','password':'pass12345','partner':'part12345'}
这就是我的代码之后的样子:
request = urllib2.Request(url, data, header)
response_xml = urllib2.urlopen(request)
response = response_xml.read()
print(response)
但如果我没有经过身份验证的用户,我得到了回复。我做错了什么?谢谢!
答案 0 :(得分:1)
试试这个:
from urllib import urlencode
from urllib2 import urlopen
args = {'codes':'12345','user':'user12345','password':'pass12345','partner':'part12345'}
conn = urlopen(url,urlencode(args))
data = conn.read()
conn.close()
print(data)