代码如下:
import SimpleHTTPServer
import SocketServer
import re
def htc(m):
return chr(int(m.group(1),16))
def urldecode(url):
rex=re.compile('%([0-9a-hA-H][0-9a-hA-H])',re.M)
return rex.sub(htc,url)
class SETHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def createHTML(self):
html = file("index.html", "r")
for line in html:
self.wfile.write(line)
def do_GET(self):
print "GET"
print self.headers;
self.createHTML()
def do_POST(self):
print "POST"
print self.headers;
length = int(self.headers.getheader('content-length'))
qs = self.rfile.read(length)
url=urldecode(qs)
print "url="
print url
self.createHTML()
Handler = SETHandler
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
测试用的index.html页面如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="http://127.0.0.1:8000/" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
在浏览器里打开http://127.0.0.1:8000/,输出如下:
GET
Accept: */*
Accept-Language: zh-cn
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
Accept-Encoding: gzip, deflate
Host: 127.0.0.1:8000
Connection: Keep-Alive
GET
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
Host: 127.0.0.1:8000
Connection: Keep-Alive
点击"login"后,输入如下:
POST
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, */*
Referer: http://127.0.0.1:8000/
Accept-Language: zh-cn
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 127.0.0.1:8000
Content-Length: 27
Connection: Keep-Alive
Cache-Control: no-cache
url=
username=yang&password=pass