2

Is there a preferred python module that could help me to send XML through a HTTP request and be able to parse the returning XML?

Takkun
  • 6,131
  • 16
  • 52
  • 69
  • Will it be a SOAP message or just something-XML message? For SOAP integration with python see [suds](https://fedorahosted.org/suds/). – joar May 22 '12 at 18:36
  • Relevant for parsing XML: http://stackoverflow.com/q/1912434/208339. I also like ElementTree. – Steve Tjoa May 22 '12 at 18:48
  • The XML will be in the format of something simple like 0 or several nestings. – Takkun May 22 '12 at 18:52

1 Answers1

6

One way would be to use urllib2:

r = urllib2.Request("http://example.com", data="<xml>spam</xml>",
                     headers={'Content-Type': 'application/xml'})
u = urllib2.urlopen(r)
response = u.read()

Note that you have to set the content-type header, or the request will be sent application/x-www-form-urlencoded.

If that's too complicated for you, then you can also use the requests library.

For parsing the response lxml is a great library, but elementtree will also do.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
mata
  • 67,110
  • 10
  • 163
  • 162
  • 5
    I strongly recommend `requests` in all cases. – Marcin May 22 '12 at 19:45
  • 1
    I keep getting the error badstatusline caused by the status being empty. Is there any way to ignore this or get the responding XML? – Takkun May 22 '12 at 19:50
  • 1
    that means your server probably doesn't return a valid http status. – mata May 22 '12 at 19:54
  • why is that a problem? Is there any other module besides httplib for sending http requests? – Takkun May 22 '12 at 19:55
  • 1
    yes, as i wrote you should try the `requests` library, it possibly can deal with a bad status better. but if you have control over the server, you should check if it's returning a valid status or why it isn't. – mata May 22 '12 at 19:58
  • using the above code I get the exact same error since urllib2 just uses httplib. I do not have control over the server. – Takkun May 22 '12 at 20:01