python内建模块发起HTTP(S)请求

118 阅读1分钟
一、Python2 httplib
简介:httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现。
httplib实现http请求
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
import httplib
host = ‘www.baidu.com’ # 注意:不能带上协议
port = 80
# 获取HTTPConnection对象
conn = httplib.HTTPConnection(host, port)
# 发起请求
conn.request("GET", "/")
# 获取返回值
res = conn.getresponse()
print res.status # 状态码
print res.read() # 返回结果
urllib、urllib2
简介:urllib 和urllib2都是接受URL请求的相关模块,但是urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。
[Python]
纯文本查看
复制代码
1
2
3
4
5
6
7
8
9
import urllib[/b]d = {
"$count":"count",
"$limit":"limit",
"$offset":"offset",
"$filter":None,
}
print urllib.urlencode(d)
结果:%24offset=offset&%24limit=limit&%24filter=None&%24count=count

[Python]
纯文本查看
复制代码
1
2
3
4
5
6
7
8
9
import json
import urllib
import urllib2
#get response
data = json.dumps(body)
conn = urllib2.Request(url, data, header)
res = urllib2.urlopen(conn)
print res
print res.read()

二、python3urllib
简介:Python3中也有urllib和urllib3两个库,其中urllib几乎是Python2中urllib和urllib2两个模块的集合,所以我们最常用的urllib模块,而urllib3则作为一个拓展模块使用。
urllib发起请求
[Python]
纯文本查看
复制代码
1
2
3
4
import urllib
from urllib import request
res = request.urlopen("http://www.baidu.com")
print(res.read())

urllib进行url编码
[Python]
纯文本查看
复制代码
1
2
3
4
5
6
import urllib
from urllib import parse
d = {"a":"1","b":"2"}
parse.urlencode(d)
结果:'a=1&b=2'

更多技术资讯可关注:itheimaGZ获取