一、HTTP请求模块
1.1 模块及区别
模块:
httplib、 httplib2
urllib、urllib2
区别:
2是1的加强版,http比url更底层。
可以理解为urllib是httplib的抽象。
1.2 httplib发送GET请求实例代码
#!/usr/bin/env python
import httplib
#connect
conn = httplib.HTTPConnection("192.168.175.130")
#request
conn.request("GET", "/get.php?id=100")
#response
r = conn.getresponse()
#output
print r.status, r.reason
print r.read()
#close
conn.close()
httplib实现CDN中的预缓存:
相当于执行:curl -x 127.0.0.1:80 http://tcp.qihooyun.cn/tcp.txt -v
#!/usr/bin/env python
import httplib
import urllib
#connect
conn = httplib.HTTPConnection("127.0.0.1", 80, timeout=60)
#request
method = "GET"
url = "/tcp.txt"
body = {}
headers = {"Host": "tcp.qihooyun.cn"}
conn.request(method, url, urllib.urlencode(body), headers)
#response
r = conn.getresponse()
#output
print r.status, r.reason
print r.read()
print r.getheaders()
#close
conn.close()
1.3 urllib、urllib2发送GET请求实例代码
#!/usr/bin/env python
#import urllib
import urllib2
#r = urllib.urlopen("http://192.168.175.130/get.php?id=100")
r = urllib2.urlopen("http://192.168.175.130/get.php?id=100")
print r.read()
1.4 urllib、urllib2发送POST请求实例代码
#!/usr/bin/env python
#import urllib
import urllib2
import json
post_data = {}
post_data['status'] = 1
post_data['info'] = "success"
post_data_json = json.dumps(post_data)
#r = urllib.urlopen("http://192.168.175.131/post.php", post_data_json)
r = urllib2.urlopen("http://192.168.175.131/post.php", post_data_json)
print(r.read())
1.5 上述get.php、post.php的代码
get.php:
<?php
if (!empty($_GET))
{
extract($_GET);
}
if (!empty($_POST))
{
extract($_POST);
}
$id=$_GET["id"];
print "php get response: ".$id;
?>
post.php:
<?php
if (!empty($_GET))
{
extract($_GET);
}
if (!empty($_POST))
{
extract($_POST);
}
$content = file_get_contents("php://input");
print "content:" . $content;
?>
二、Web服务器模块
2.1 模块及区别
SimpleHTTPServer:包含执行GET和HEAD请求的SimpleHTTPRequestHandler类。
BaseHTTPServer:提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler。
CGIHTTPServer:包含处理POST请求和执行CGIHTTPRequestHandler类。2.2 实例代码
建立最简单的Web服务器:
python -m SimpleHTTPServer
python -m CGIHTTPServer 8080
默认端口8000
参考资料:
用Python建立最简单的Web服务器:http://www.cnblogs.com/xuxn/archive/2011/02/14/build-simple-web-server-with-python.html
Python的HTTP服务:http://blog.csdn.net/kevin_darkelf/article/details/40980333
Python发送HTTP请求:http://blog.csdn.net/yangchao228/article/details/6210413