How to POST an xml element in python

∥☆過路亽.° 提交于 2019-12-02 19:33:44

If this is your own API, I would consider POSTing as application/xml. The default is application/x-www-form-urlencoded, which is meant for HTML form data, not a single XML document.

req = urllib2.Request(url=url, 
                      data=xml_string, 
                      headers={'Content-Type': 'application/xml'})
urllib2.urlopen(req)
Vladimir Jirasek

Here is a full example (snippet) for sending post data (xml) to an URL:

def execQualysAction(username,password,url,request_data):
  import urllib,urrlib2
  xml_output = None 
  try:
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')  
    headers = {'X-Requested-With' : 'urllib2','Content-Type': 'application/xml','Authorization': 'Basic %s' % base64string}
    req = urllib2.Request(url=url,data=request_data,headers=headers)
    response = urllib2.urlopen(req,timeout=int(TIMEOUT))
    xml_output = response.read()
    if args.verbose>1:
      print "Result of executing action request",request_data,"is:",xml_output
  except:
    xml_output = '<RESULT></RESULT>'
    traceback.print_exc(file=sys.stdout)
    print '-'*60

finally:

return xml_output

No, I think that's probably the best way to do it - it's short and simple, what more could you ask for? Obviously the XML has to be converted to a string at some point, and unless you're using an XML library with builtin support for POSTing to a URL (which xml.etree is not), you'll have to do it yourself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!