Jageee
Jageee

Reputation: 1

Receive HTTP POST response by python

I use the following example: http://www.w3schools.com/php/php_forms.asp

When I run it from browser, I see the results in the browser:

Welcome John
Your email address is [email protected]

When I run python POST http request:

import httplib, urllib
params = urllib.urlencode({'@name': 'John','@email': '[email protected]'})
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/html"}
conn = httplib.HTTPConnection("10.0.0.201")
conn.request("POST","/welcome.php",params, headers)
response = conn.getresponse()
print "Status"
print response.status
print "Reason"
print response.reason
print "Read"
print response.read()
conn.close()

I see the following:

Status
200
Reason
OK
Read
<html>
<body>

Welcome <br>
Your email address is: 
</body>
</html>

The question is: How to receive POST request data in python?

Upvotes: 0

Views: 1618

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1122342

You are using the wrong form names and the wrong HTTP method. There are no @ characters at their starts:

params = urllib.urlencode({'name': 'John','email': '[email protected]'})

Next, the form you point to uses GET, not POST as the handling method, so you'll have to add these parameters to the URL instead:

conn.request("GET", "/welcome.php?" + params, '', headers)

You are doing yourself a disservice by trying to drive the HTTPConnection() manually. You could use urllib2.urlopen() instead for example:

from urllib2 import urlopen
from urllib import urlencode

params = urlencode({'name': 'John','email': '[email protected]'})
response = urlopen('http://10.0.0.201/welcome.php?' + params)
print response.read()

or you could make use of the requests library (separate install) to make it yourself much easier still:

import requests

params = {'name': 'John','email': '[email protected]'}
response = requests.get('http://10.0.0.201/welcome.php', params=params)
print response.content

Upvotes: 2

Jageee
Jageee

Reputation: 1

I just removed the "@" and it works:

Status
200
Reason
OK
Read
<html>
<body>

Welcome John<br>
Your email address is: [email protected]
</body>
</html>

Thank you Martijn Pieters.

As for POST method, i used the example for infrastructure testing purposes. Finally i need to fill mysql database and retrieve data from it over php using python script. What is the best method for it? Why is HTTPConnection() not recommended?

Upvotes: 0

Muntaser Ahmed
Muntaser Ahmed

Reputation: 4647

Instead of using urllib, use the requests library as Martijn suggested. It will make things much simpler.

Check out the documentation: http://docs.python-requests.org/en/latest/user/quickstart/

Upvotes: 0

Related Questions