最近学习了python的一些服务器端编程,记录在此。
发送get/post请求
# coding:utf-8import httplib,urllib #加载模块#urllib可以打开网站去拿#res = urllib.urlopen('http://baidu.com');#print res.headers#定义需要进行发送的数据 params = urllib.urlencode({'param':'6'});#定义一些文件头 headers = {"Content-Type":"application/x-mand)+str(self.headers.dict)+data)addr = ('',8765)server = HTTPServer(addr,RequestHandler)server.serve_forever()注意这里,python把response的消息体记录在了rfile中。BaseHpptServer没有实现do_POST方法,需要自己重写。之后我们新建类RequestHandler,继承自 baseHTTPServer 重写do_POST方法,读出rfile的内容即可。
但是要注意,发送端必须指定content-length.若不指定,程序就会卡在rfile.read()上,不知道读取多少。
参考手册 http://docs.python.org/2/library/basehttpserver.html