dpyic24480 2014-09-15 18:18
浏览 160

通过python接收HTTP POST响应

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?

  • 写回答

3条回答 默认 最新

  • doumi4676 2014-09-15 18:20
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了