Python , Send xml data as post request

01 Jul

So I needed to send xml data to a service. initially I did it like this:

import urllib, urllib2
url = "some url"
param_data = {'businesses': xml}
params = urllib.urlencode(param_data)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
opener.addheaders = [('Accept', 'application/xml'), ('Content-Type', 'application/xml'),]
resp = urllib2.urlopen(url, params)

Essentially sending the xml as a param.

This works fine.
The consuming service however does not expect a post param. Instead it expects the xml as data in the body of the post. To be honest this is the first time I had come across this. Weird.

So after a bit of complaining, nagging, googling, interrogating urllib and asking a much more knowledgeable coder. I changed the last bit to this:

req = urllib2.Request(url)
resp = urllib2.urlopen(req)

I used the xml as is without urlencoding it.

So this change will add the xml to the post body.

To add a set of params:

param_data = {'stuff':"things", "more_stuff": "more_things"}
params = urllib.urlencode(param_data)

req = urllib2.Request(url)
resp = urllib2.urlopen(req)

Nice and simple. The complicated things usually are.

For more reading up on urllib:

Official python docs

Doug Hellman stuff

Hope this helped?

Leave a comment

Posted by on July 1, 2011 in Uncategorized


Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: