Python 基于urllib.request封装http协议类
基于urllib.request封装http协议类
by:授客QQ:1033553122
测试环境:
Python版本:Python 3.3
代码实践
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
import urllib.request
import http.cookiejar
import urllib.parse
class MyHttp:
'''配置要测试请求服务器的ip、端口、域名等信息,封装http请求方法,http头设置'''
def __init__(self, protocol, host, port, header = {}):
# 从配置文件中读取接口服务器IP、域名,端口
self.protocol = protocol
self.host = host
self.port = port
self.headers = header # http 头
#install cookie #自动管理cookie
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)
def set_host(self, host):
self.host = host
def get_host(self):
return self.host
def get_protocol(self):
return self.protocol
def set_port(self, port):
self.port = port
def get_port(self):
return self.port
# 设置http头
def set_header(self, headers):
self.headers = headers
# 封装HTTP GET请求方法
def get(self, url, params=''):
url = self.protocol + '://' + self.host + ':' + str(self.port) + url + params
print('发起的请求为:%s' % url)
request = urllib.request.Request(url, headers=self.headers)
try:
response = urllib.request.urlopen(request)
response = response.read()
return response
except Exception as e:
print('发送请求失败,原因:%s' % e)
return None
# 封装HTTP POST请求方法
def post(self, url, data=''):
url = self.protocol + '://' + self.host + ':' + str(self.port) + url
print('发起的请求为:%s' % url)
request = urllib.request.Request(url, headers=self.headers)
try:
response = urllib.request.urlopen(request, data)
response = response.read()
return response
except Exception as e:
print('发送请求失败,原因:%s' % e)
return None
# 封装HTTP xxx请求方法
# 自由扩展
案例1:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
from httpprotocol import MyHttp
if __name__ == '__main__':
http = MyHttp('https', 'www.baifubao.com', 443)
params = {"cmd":1059,"callback":"phone", "phone":"15850781443"}
params = urllib.parse.urlencode(params)
response = http.get('/callback?', params)
print(response)
输出response内容如下:
b'phone({"meta":{"result":"0","result_info":"","jump_url":""},"data":{"operator":"\\u79fb\\u52a8","area":"\\u6c5f\\u82cf","area_operator":"\\u6c5f\\u82cf\\u79fb\\u52a8","support_price":{"100":"115","500":"507","1000":"1000","2000":"2000","3000":"2996","5000":"4994","10000":"9989","20000":"19979","30000":"29969","50000":"49948"}}})'
如上,返回Unicode编码的数据:“"\\u79fb\\u52a8",……”,
解决方法:输出前先解码,如下
response = response.decode('unicode_escape')
print(response)
解码后的输出如下:
phone({"meta":{"result":"0","result_info":"","jump_url":""},"data":{"operator":"移动","area":"江苏","area_operator":"江苏移动","support_price":{"100":"115","500":"507","1000":"1000","2000":"2000","3000":"2996","5000":"4994","10000":"9989","20000":"19979","30000":"29969","50000":"49948"}}})
案例2:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
from httpprotocol import MyHttp
if __name__ == '__main__':
http = MyHttp('http', 'www.webxml.com.cn', 80) #
header = {'Content-Type':'text/xml','charset':'utf-8'}
http.set_header(header)
params = '''<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://WebXml.com.cn/">
<soapenv:Header/>
<soapenv:Body>
<web:getSupportProvince/>
</soapenv:Body>
</soapenv:Envelope>'''
params = params.encode(encoding='UTF-8')
response = http.post('/WebServices/WeatherWebService.asmx?', params)
print(response)
说明:
1、params = params.encode(encoding='UTF-8') # 如果未添加该行代码,会报错如下:
POST data should be bytes or an iterable of bytes. It cannot be of type str.
2、
header = {'Content-Type':'text/xml','charset':'utf-8'}
http.set_header(header)
以上两行代码,为请求添加请求头,如果未添加,则会报错,如下:
HTTP Error 415: Unsupported Media Type
3、输出response,部分内容如下:
\xe7\x9b\xb4\xe8\xbe\x96\xe5\xb8\x82\xe7\x89\xb9\xe5\x88\xab\xe8\xa1\x8c\xe6\x94\xbf\xe5\x8c\xba……
如上,返回十六进制(\x表示16进制)的字符e7,9b等
解决方法:输出前先解码,如下
response = response.decode('utf-8')
print(response)
解码后的输出结果:
直辖市特别行政区……
案例3:
import json
from httpprotocol import MyHttp
if __name__ == '__main__':
http = MyHttp('http', 'info.so.360.cn', 80)
header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}
http = MyHttp('http', 'info.so.360.cn', 80)
http.set_header(header)
url = '/index.php?g=Embody&m=Index&a=submit'
parmas = '{"websitetype":"博客论坛","url":"http://blog.sina.com.cn/ishouke","email":"1033553122@40qq.com","checkcode":"rkqj"}'
parmas = parmas.encode('utf-8')
response = http.post(url,parmas)
print(response.decode('utf-8'))
说明:如果服务器支持的内容类型(‘Content-Type’)为json则要修改请求头,如下
header = {'Content-Type':'application/json','charset':'utf-8'}
Python 基于urllib.request封装http协议类的更多相关文章
- Python Spider - urllib.request
import urllib.request import urllib.parse import json proxy_support = urllib.request.ProxyHandler({' ...
- python之urllib.request.urlopen(url)报错urllib.error.HTTPError: HTTP Error 403: Forbidden处理及引申浏览器User Agent处理
最近在跟着院内大神学习python的过程中,发现使用urllib.request.urlopen(url)请求服务器是报错: 在园子里找原因,发现原因为: 只会收到一个单纯的对于该页面访问的请求,但是 ...
- 通过python的urllib.request库来爬取一只猫
我们实验的网站很简单,就是一个关于猫的图片的网站:http://placekitten.com 代码如下: import urllib.request respond = urllib.request ...
- python爬虫 - Urllib库及cookie的使用
http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...
- python爬虫---urllib库的基本用法
urllib是python自带的请求库,各种功能相比较之下也是比较完备的,urllib库包含了一下四个模块: urllib.request 请求模块 urllib.error 异常处理模块 u ...
- python基于http协议编程:httplib,urllib和urllib2<转>
httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现. httplib.HTTPConnecti ...
- 基于小程序请求接口 wx.request 封装的类 axios 请求
基于小程序请求接口 wx.request 封装的类 axios 请求 Introduction wx.request 的配置.axios 的调用方式 源码戳我 feature 支持 wx.reques ...
- Python urllib Request 用法
转载自:https://blog.csdn.net/ywy0ywy/article/details/52733839 python2.7 httplib, urllib, urllib2, reque ...
- python中urllib, urllib2,urllib3, httplib,httplib2, request的区别
permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...
随机推荐
- win10 插入16k采样的耳机无法播放和录音的问题定位
平时做智能耳机,需要经常在windows上测试不同采样率的声音信号.可是,最近在16k双声道输入的情况下, 无论系统都使用该耳机进行播放,该问题思索了好久,一直没有解决办法. 今天无意中使用了wind ...
- git 服务器搭建及提交代码检查
本地 git 服务,通常都会选择 gitlab.本人最先也是选择 gitlab,在 centos7 上按照官网的步骤进行安装,下载的速度难以忍受,无奈放弃.最终选择在 docker 中安装 gogs ...
- NodeJS简单爬虫
NodeJS简单爬虫 最近一直在追火星的一本书,然后每次都要去网站看,感觉很麻烦,于是,想起用爬虫爬取章节,务实派,说干就干! 爬取思路 1.该网站的页面呈现出一定的规律 2.使用NodeJS的req ...
- 写在19年初的后端社招面试经历(两年经验): 蚂蚁 头条 PingCAP
去年(18年)年底想出来看看机会,最后很幸运地拿到了 PingCAP,今日头条的 offer 以及蚂蚁金服的口头 offer.想着可以总结一下经验,分享一下自己这一段"骑驴找马"过 ...
- [P4318] 完全平方数
想不出什么办法能直接算的(别跟我提分块打表),不如二分答案吧:设\(f(x)=\sum_{i=1}^n [i不是"完全平方数"]\), 显然f(x)与x正相关.再结合筛法.容斥,不 ...
- 用C#学习数据结构之线性表
什么是线性表 线性表是最简单.最基本.最常用的数据结构.线性表是线性结构的抽象(Abstract),线性结构的特点是结构中的数据元素之间存在一对一的线性关系.这种一对一的关系指的是数据元素之间的位置关 ...
- Docker 本地导入镜像/保存镜像/载入镜像/删除镜像
1.Docker导入本地镜像 有时候我们自己在本地或者其它小伙伴电脑上拷贝了一份镜像,有了这个镜像之后,我们可以把本地的镜像导入,使用docker import 命令. 例如这里下载了一个 aliba ...
- 使用GitHub搭建个人博客
博客已经从博客园慢慢搬到GitHub 上,可能在博客园上显示不是很规整,可以移步到另外的一个上面看 Blog 两边博客同时更新. 欢迎各位star 和 follower 搭建过程 在搭建博客时候也踩 ...
- [Noip2015PJ] 求和
Description 一条狭长的纸带被均匀划分出了 \(n\) 个格子,格子编号从 \(1\) 到 \(n\) .每个格子上都染了一种颜色 \(color_i\) 用 \([1,m]\) 当中的一个 ...
- Java语法之反射
一.反射机制 在前面Java语法之注解自定义注解时我们也有提到反射,要获取类方法和字段的注解信息,必须通过Java的反射技术来获取 Annotation对象.那什么是反射呢?JAVA反射机制是在运行状 ...