我使用以下示例:http://www.w3schools.com/php/php_forms.asp
当我从浏览器运行它时,我在浏览器中看到结果:
Welcome John
Your email address is john.doe@example.com
当我运行python POST http请求时:
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()
我看到以下内容:
Status
200
Reason
OK
Read
<html>
<body>
Welcome <br>
Your email address is:
</body>
</html>
问题是:如何在python中接收POST请求数据?
您使用了错误的表单名称和错误的HTTP方法。起始处没有@
字符:
params = urllib.urlencode({'name': 'John','email': 'John.doe@example.com'})
接下来,您指向的表单使用GET,而不是POST作为处理方法,因此您必须将这些参数添加到URL中:
conn.request("GET", "/welcome.php?" + params, '', headers)
您试图手动驱动HTTPConnection()
是在伤害自己。您可以使用urllib2.urlopen()
,例如:
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()
或者你可以使用requests
库(单独安装),让自己更容易:
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
不要使用urllib
,而是按照Martijn的建议使用requests
库。这会让事情变得简单得多。
查看文档:http://docs.python-requests.org/en/latest/user/quickstart/
我刚刚删除了"@",它起作用了:
Status
200
Reason
OK
Read
<html>
<body>
Welcome John<br>
Your email address is: John.doe@example.com
</body>
</html>
谢谢Martijn Pieters。
至于POST方法,我使用该示例进行基础设施测试。最后,我需要填充mysql数据库,并使用python脚本通过php从中检索数据。最好的方法是什么?为什么不建议使用HTTPConnection()?