python 简单服务器以及请求

 1 #get请求
 2 #
 3 #coding=utf8
 4  
 5 import httplib
 6  
 7 httpClient = None
 8  
 9 try:
10     httpClient = httplib.HTTPConnection('localhost', 8989, timeout=30)
11     httpClient.request('GET', '/index.html')
12  
13     #response是HTTPResponse对象
14     response = httpClient.getresponse()
15     print response.status
16     print response.reason
17     print response.read()
18 except Exception, e:
19     print e
20 finally:
21     if httpClient:
22         httpClient.close()
 1 #post请求
 2  
 3 import httplib, urllib
 4  
 5 httpClient = None
 6 try:
 7     params = urllib.urlencode({'name': 'tom', 'age': 22})
 8     headers = {"Content-type": "application/x-www-form-urlencoded"
 9                     , "Accept": "text/plain"}
10  
11     httpClient = httplib.HTTPConnection("localhost", 8989, timeout=30)
12     httpClient.request("POST", "/index.html", params, headers)
13  
14     response = httpClient.getresponse()
15     print response.status
16     print response.reason
17     print response.read()
18     print response.getheaders() #获取头信息
19 except Exception, e:
20     print e
21 finally:
22     if httpClient:
23         httpClient.close()
1 john:myserver fumeng$ pwd
2 /Users/fumeng/myserver
3 john:myserver fumeng$ python -m CGIHTTPServer 8989
4 Serving HTTP on 0.0.0.0 port 8989 ...

 

 1 <!-- html 代码 -->
 2 <!DOCTYPE HTML>
 3 <html>
 4     <head>
 5         <title>
 6             python cgi
 7         </title>
 8     </head>
 9     <body>
10     <p>test for python cgi server</p>
11         <form action="/cgi-bin/index.py">            
12             <label for="">name:</label><input type="text" name="name" >
13             <input type="submit">
14         </form>
15     </body>
16 </html>
 1 # -*- coding: utf-8 -*-
 2             
 3 import cgi
 4             
 5 header = 'Content-Type: text/html\n\n'
 6             
 7 html = '<h3>接受处理表单数据\n</h3>'
 8 #打印返回的内容
 9 print header
10 print html
11 # 接受表达提交的数据
12 form = cgi.FieldStorage()
13             
14 print '接收表达get的数据 :',form  
15             
16 print '<p />'
17             
18 # 解析处理提交的数据
19 content = form['name'].value
20             
21 formhtml = '''
22 <label for="">your name:</label><input type="name" value="%s">
23 '''
24             
25 print formhtml % (content)

 

posted on 2015-04-26 20:16  mmdsnb  阅读(133)  评论(0)    收藏  举报

导航