简体   繁体   中英

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 john.doe@example.com

When I run python POST http request:

import httplib, urllib
params = urllib.urlencode({'@name': 'John','@email': 'John.doe@example.com'})
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?

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': 'John.doe@example.com'})

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': 'John.doe@example.com'})
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': 'John.doe@example.com'}
response = requests.get('http://10.0.0.201/welcome.php', params=params)
print response.content

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/

I just removed the "@" and it works:

Status
200
Reason
OK
Read
<html>
<body>

Welcome John<br>
Your email address is: John.doe@example.com
</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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM