Making a POST call instead of GET using urllib2

alfonso.kim picture alfonso.kim · Jun 14, 2011 · Viewed 186.7k times · Source

There's a lot of stuff out there on urllib2 and POST calls, but I'm stuck on a problem.

I'm trying to do a simple POST call to a service:

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
content = urllib2.urlopen(url=url, data=data).read()
print content

I can see the server logs and it says that I'm doing GET calls, when I'm sending the data argument to urlopen.

The library is raising an 404 error (not found), which is correct for a GET call, POST calls are processed well (I'm also trying with a POST within a HTML form).

Answer

Gregg picture Gregg · Jun 14, 2011

This may have been answered before: Python URLLib / URLLib2 POST.

Your server is likely performing a 302 redirect from http://myserver/post_service to http://myserver/post_service/. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url to http://myserver/post_service/.