How to use POST Method

There are two methods while using web. One is GET and the other is POST. We normally use GET. In a GET method we send a request to the server in the form of an url and in back we get a response in the screen as a web page. But we use POST method to post something to a server. There is no response in the form of a web page. We can ask for a response about the status of our post. The following paragraph discribes how we can use a POST method.

To use the POST method we need two libraries of Python. One is ‘httplib’ and the other is ‘urllib’. ‘urllib’ is used to encode the post documents within the url. And ‘httplib’ is used to establish connection and to tell the server that the coming method is a POST method. The POST request contain 4 parameters: the method(here its POST), the url to which the item is to be posted, parameters or payload containing the items to be posted and the headers. The parameters are of a dictionary form. i.e. it contain a key and a corresponding value. At the server side the value can be retrieved using these keys. The parameter is encoded using ‘urlencode’ method of ‘urllib’.

>>> import urllib, httplib

>>> params = urllib.urlencode({‘name’:’john’, ‘place’:’kerala’})

The header describe the content type.

>>> headers = (“content-type”: “application/x-www-form-urlencoded”, “Accept”:”text/plain”)

Now create an instance of HTTPConnection to create a connection with the server. In my example I took my local machine as my server.

>>> conn = httplib.HTTPConnection(“localhost:8080”)

>>> conn.request(“POST”, “/xyz”, params, headers)

Now the POST request is successfully posted. If we want to know the status of our post

>>> response = conn.getresponse()

>>> print response.status, response.reason

If our post was successful the output will be ‘ok’ ‘200’. To read the data we have posted

>>> data =

>>> print data


About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on September 8, 2010, in Python. Bookmark the permalink. 1 Comment.

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: