我在python lol中总共花了30分钟,所以在回答lol时要考虑到这一点:
我试图发送一个带有主体的httppost请求并读取响应。我在Windows10上使用Python3.6.5。到目前为止,我得到的是:
进口http.客户端 进口xml.dom.minidom在
HOST = "www.mysite.com"
API_URL = "/service"
def do_request(xml_location):
request = open(xml_location, "r").read()
webservice = http.client.HTTPConnection(HOST)
webservice.request("POST", API_URL)
webservice.putheader("Host", HOST)
webservice.putheader("User-Agent", "Python Post")
webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
webservice.putheader("Content-length", "%d" % len(request))
webservice.endheaders()
webservice.send(request)
statuscode, statusmessage, header = webservice.getreply()
result = webservice.getfile().read()
resultxml = xml.dom.minidom.parseString(result)
print (statuscode, statusmessage, header)
print (resultxml.toprettyxml())
with open("output-%s" % xml_location, "w") as xmlfile:
xmlfile.write(resultxml.toprettyxml())
do_request("test.xml")
在测试.xml包含XML请求。当我运行时,我得到一个错误:
^{pr2}$
您的问题是您混淆了^{} 和{a2}方法。(毫不奇怪,考虑到文档的简洁性和稀疏性……Python中的大多数模块的文档都比这要好得多,所以不要让这让您担心未来。)
request
方法是一个方便的函数,可以一次性添加请求行、所有头和数据。这样做之后,添加头就太晚了,因此会出现错误消息。在所以,你可以用任何一种方法来解决它。在
(1)将其更改为使用
putrequest
。我知道在文档中没有使用putrequest
或putheader
的例子,但它看起来像这样:(2)将其更改为使用
^{pr2}$request
。文档中的所有示例都是这样做的;您只需要建立一个标题dict来传递给它:(3)在文件顶部阅读:
对于大多数实际情况,如果您可以使用第三方库,则可以使用
requests
,如果不能,则使用urllib.request
。这两种方法都更简单,而且有更好的文档记录。在相关问题 更多 >
编程相关推荐