Python 基于urllib.request封装http协议类

简介: Python 基于urllib.request封装http协议类

基于urllib.request封装http协议类


测试环境:

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)


 

说明:

1params = 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'}

目录
相关文章
|
6月前
|
缓存 负载均衡 网络协议
HTTP 与 SOCKS5 代理协议:企业级选型指南与工程化实践
面向企业网络与数据团队的代理协议选型与治理指南,基于流量特征选择HTTP或SOCKS5协议,通过多协议网关统一出站,结合托管网络降低复杂度,实现稳定吞吐、可预测时延与合规落地。
|
7月前
|
缓存 供应链 芯片
电子元件类商品 item_get - 商品详情接口深度分析及 Python 实现
电子元件商品接口需精准返回型号参数、规格属性、认证及库存等专业数据,支持供应链管理与采购决策。本文详解其接口特性、数据结构与Python实现方案。
|
8月前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
759 2
|
8月前
|
应用服务中间件
HTTP协议中常见的状态码
HTTP协议状态码分为1xx、2xx、3xx、4xx、5xx五类,常见状态码包括:101(请求已接受)、200(请求成功)、302(重定向)、400(请求错误)、401(未认证)、403(无权限)、404(资源不存在),以及500(服务器错误)、502(网关错误)、503(服务不可用)、504(网关超时)等。
537 0
|
8月前
|
网络协议 安全 网络安全
什么是HTTP协议
HTTP协议是超文本传输协议,基于TCP,规定了客户端与服务器端通信规则,但数据以明文传输,安全性低。HTTPS则通过SSL加密保障数据安全。两者默认端口不同,HTTP为80,HTTPS为443。HTTPS安全性更高,但消耗更多服务器资源。
355 0
|
8月前
|
数据采集 Web App开发 JSON
Python爬虫基本原理与HTTP协议详解:从入门到实践
本文介绍了Python爬虫的核心知识,涵盖HTTP协议基础、请求与响应流程、常用库(如requests、BeautifulSoup)、反爬应对策略及实战案例(如爬取豆瓣电影Top250),帮助读者系统掌握数据采集技能。
697 0
|
9月前
|
存储 网络协议 安全
HTTP 协议及会话跟踪机制详解
本文详解了 HTTP 协议的核心知识,包括其定义(超文本传输协议,基于 TCP,规定客户端与服务器通信规则)及与 HTTPS 的区别(安全性、端口、资源消耗)。 介绍了 GET 与 POST 请求的差异(参数限制、安全性、应用场景),以及 Restful 风格(通过 URL 定位资源,请求方式决定操作)。列举了常见 HTTP 状态码(如 200 成功、404 资源未找到),对比了转发与重定向的区别(服务器端一次请求 vs 客户端两次请求)。 还阐述了会话跟踪机制:Cookie 基于客户端存储,通过Set-Cookie和Cookie头实现,安全性较低;Session 基于服务端存储,依赖 C
746 1
|
8月前
|
缓存 网络协议 UED
深度解析HTTP协议从版本0.9至3.0的演进和特性。
总的来说,HTTP的演进是互联网技术不断发展和需求日益增长的结果。每一次重要更新都旨在优化性能,增进用户体验,适应新的应用场景,而且保证了向后兼容,让互联网的基础架构得以稳定发展。随着网络技术继续进步,我们可以预期HTTP协议在未来还会继续演化。
959 0
|
9月前
|
XML 安全 网络架构
深度对比SOAP与HTTP协议:详细理解它们的工作原理和差异
在设计服务和系统交云策略时,考虑到上述差异是至关重要的。SOAP适合需要高安全性、可靠性和事务支持的企业级应用。而HTTP适合Web界面浏览、RESTful服务和需要快速响应的轻量级通信。根据具体需求和上下文,开发者可以选择合适的协议以实现最优的系统性能和用户体验。
680 0

推荐镜像

更多