Recently learned some of Python's server-side programming, recorded here.
Send Get/post Request
# coding:utf-8
Import httplib,urllib #加载模块
#urllib可以打开网站去拿
#res = Urllib.urlopen (' http://baidu.com ');
#print res.headers
#定义需要进行发送的数据
params = urllib.urlencode ({' param ': ' 6 '});
#定义一些文件头
headers = {"Content-type": "application/x-www-form-urlencoded",
"Connection": "Keep-alive", ' Content-length ': ';
#与网站构建一个连接
conn = httplib. Httpconnection ("localhost:8765");
#开始进行数据提交 can also use get for
conn.request (method= "POST", url= "/", body=params,headers=headers);
#返回处理后的数据
response = Conn.getresponse ();
Print Response.read ()
#判断是否提交成功
If response.status =
print "published successfully! ^_^!";
else:
print "Publish failed \^0^/";
#关闭连接
conn.close ();
The Urllib module can be used to send HTTP requests conveniently. URLLIB Reference Manual
Http://docs.python.org/2/library/urllib.html
Establish HTTP server, process get,post request
# Coding:utf-8 from basehttpserver Import Httpserver,basehttprequesthandler class RequestHandler ( Basehttprequesthandler): def _writeheaders (self): print self.path print self.headers self.send_response (200)
;
Self.send_header (' Content-type ', ' text/html '); Self.end_headers () def do_head (self): Self._writeheaders () def do_get (self): self._writeheaders () Self.wfi Le.write ("" "<! DOCTYPE html>
Note that Python records the response message body in the rfile. Basehpptserver does not implement the Do_post method and needs to rewrite it yourself. Then we create a new class RequestHandler, inherit from Basehttpserver rewrite Do_post method, read out rfile content.
Note, however, that the sender must specify the content-length. If not specified, the program will be stuck on the Rfile.read (), do not know how much read.
Reference manual Http://docs.python.org/2/library/basehttpserver.html