Python实现HTTP请求和响应
1.Python CGI响应HTTPget/post请求,test.py(Python CGI 配置请查看上篇文章)
#!/usr/bin/Python
import cgi
def main():
print "Content-type: text/html\n"
form = cgi.FieldStorage()
if form.has_key("ClientRequest") and form["ClientRequest"].value != "":
print " Hello", form["ClientRequest"].value, "
"
else:
print " Error!
"
main()
2.get请求
import urllib
import urllib2
test_data = {'ClientRequest': 'aaaa', 'b': 'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
# requrl = "http://baidu.com"
requrl = "http://192.168.0.148/test.py"
req = urllib2.Request(url=requrl, data=test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
3.post请求
import urllib
import urllib2
test_data = {'ClientRequest': 'aaaa', 'bd': 'bbdbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "http://192.168.0.148/test.py"
req = urllib2.Request(url=requrl, data=test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
下一篇,打算模拟Python访问数据库查询返回值。