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'}

目录
相关文章
|
27天前
|
测试技术 Python
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
103 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
|
2月前
|
JSON 数据格式
.net HTTP请求类封装
`HttpRequestHelper` 是一个用于简化 HTTP 请求的辅助类,支持发送 GET 和 POST 请求。它使用 `HttpClient` 发起请求,并通过 `Newtonsoft.Json` 处理 JSON 数据。示例展示了如何使用该类发送请求并处理响应。注意事项包括:简单的错误处理、需安装 `Newtonsoft.Json` 依赖,以及建议重用 `HttpClient` 实例以优化性能。
89 2
|
2月前
|
数据采集 存储 XML
python实战——使用代理IP批量获取手机类电商数据
本文介绍了如何使用代理IP批量获取华为荣耀Magic7 Pro手机在电商网站的商品数据,包括名称、价格、销量和用户评价等。通过Python实现自动化采集,并存储到本地文件中。使用青果网络的代理IP服务,可以提高数据采集的安全性和效率,确保数据的多样性和准确性。文中详细描述了准备工作、API鉴权、代理授权及获取接口的过程,并提供了代码示例,帮助读者快速上手。手机数据来源为京东(item.jd.com),代理IP资源来自青果网络(qg.net)。
|
4月前
|
Java C++ Python
Python基础---类
【10月更文挑战第10天】Python类的定义
50 2
|
4月前
|
索引 Python
python-类属性操作
【10月更文挑战第11天】 python类属性操作列举
45 1
WK
|
4月前
|
Python
Python类命名
在Python编程中,类命名至关重要,影响代码的可读性和维护性。建议使用大写驼峰命名法(如Employee),确保名称简洁且具描述性,避免使用内置类型名及单字母或数字开头,遵循PEP 8风格指南,保持项目内命名风格一致。
WK
36 0
|
4月前
|
程序员 开发者 Python
深度解析Python中的元编程:从装饰器到自定义类创建工具
【10月更文挑战第5天】在现代软件开发中,元编程是一种高级技术,它允许程序员编写能够生成或修改其他程序的代码。这使得开发者可以更灵活地控制和扩展他们的应用逻辑。Python作为一种动态类型语言,提供了丰富的元编程特性,如装饰器、元类以及动态函数和类的创建等。本文将深入探讨这些特性,并通过具体的代码示例来展示如何有效地利用它们。
81 0
|
数据采集 Python
python网络爬虫urllib.request模块get请求示例
python网络爬虫urllib.request模块get请求示例
205 0
|
2月前
|
人工智能 数据可视化 数据挖掘
探索Python编程:从基础到高级
在这篇文章中,我们将一起深入探索Python编程的世界。无论你是初学者还是有经验的程序员,都可以从中获得新的知识和技能。我们将从Python的基础语法开始,然后逐步过渡到更复杂的主题,如面向对象编程、异常处理和模块使用。最后,我们将通过一些实际的代码示例,来展示如何应用这些知识解决实际问题。让我们一起开启Python编程的旅程吧!
|
2月前
|
存储 数据采集 人工智能
Python编程入门:从零基础到实战应用
本文是一篇面向初学者的Python编程教程,旨在帮助读者从零开始学习Python编程语言。文章首先介绍了Python的基本概念和特点,然后通过一个简单的例子展示了如何编写Python代码。接下来,文章详细介绍了Python的数据类型、变量、运算符、控制结构、函数等基本语法知识。最后,文章通过一个实战项目——制作一个简单的计算器程序,帮助读者巩固所学知识并提高编程技能。

热门文章

最新文章