Python – Post data to Web Service that is expecting array data

I tried posting JSON data to a PHP web service that was expecting POST params in the form of an array. But somehow – the service didn’t like getting JSON data. So I used the urlencode method of urllib2 to encode the JSON in the required format and posted it. It worked well. The other thing that is worth mentioning is the header information that should be {‘Content-type’: ‘application/x-www-form-urlencoded’, ‘Accept’ : ‘text/plain’}. Here’s some sample code that might be useful:

import json
import urllib
import urllib2

url = "https://hostname/service.api"
data = {
"function": "service_method",
"timestamp": "1369166866",
"user": "varun.verma@email.com"
}

req = urllib2.Request(url, urllib.urlencode(data), headers={'Content-type': 'application/x-www-form-urlencoded', 'Accept' : 'text/plain'})
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
Advertisements

One thought on “Python – Post data to Web Service that is expecting array data

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s