基于urllib.request封装http协议类

by:授客QQ1033553122

测试环境:

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协议类的更多相关文章

  1. Python Spider - urllib.request

    import urllib.request import urllib.parse import json proxy_support = urllib.request.ProxyHandler({' ...

  2. python之urllib.request.urlopen(url)报错urllib.error.HTTPError: HTTP Error 403: Forbidden处理及引申浏览器User Agent处理

    最近在跟着院内大神学习python的过程中,发现使用urllib.request.urlopen(url)请求服务器是报错: 在园子里找原因,发现原因为: 只会收到一个单纯的对于该页面访问的请求,但是 ...

  3. 通过python的urllib.request库来爬取一只猫

    我们实验的网站很简单,就是一个关于猫的图片的网站:http://placekitten.com 代码如下: import urllib.request respond = urllib.request ...

  4. python爬虫 - Urllib库及cookie的使用

    http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...

  5. python爬虫---urllib库的基本用法

    urllib是python自带的请求库,各种功能相比较之下也是比较完备的,urllib库包含了一下四个模块: urllib.request   请求模块 urllib.error   异常处理模块 u ...

  6. python基于http协议编程:httplib,urllib和urllib2<转>

    httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现. httplib.HTTPConnecti ...

  7. 基于小程序请求接口 wx.request 封装的类 axios 请求

    基于小程序请求接口 wx.request 封装的类 axios 请求 Introduction wx.request 的配置.axios 的调用方式 源码戳我 feature 支持 wx.reques ...

  8. Python urllib Request 用法

    转载自:https://blog.csdn.net/ywy0ywy/article/details/52733839 python2.7 httplib, urllib, urllib2, reque ...

  9. python中urllib, urllib2,urllib3, httplib,httplib2, request的区别

    permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...

随机推荐

  1. WIN10下Prolific USB-to-Serial Comm Port驱动

    最近在安装Prlific的时候,通过电脑自动安装启动后,发现系统无法识别,如下图所示: 还以为是驱动比较老,没有及时更新导致的,去官网下载最新的驱动,发现了这个列表: 这个驱动不支持win10. 后来 ...

  2. 机器学习技法笔记:11 Gradient Boosted Decision Tree

    Roadmap Adaptive Boosted Decision Tree Optimization View of AdaBoost Gradient Boosting Summary of Ag ...

  3. LeetCode: 102_Binary Tree Level Order Traversal | 二叉树自顶向下的层次遍历 | Easy

    题目:Binay Tree Level Order Traversal Given a binary tree, return the level order traversal of its nod ...

  4. SQL Server性能优化(15)选择合适的索引

    一.关于聚集索引列的选择(参考) 1. 聚集索引所在的列,或者列的组合最好是唯一的. 当我们创建的聚集索引的值不唯一时,SQL Server则无法仅仅通过聚集索引列(也就是关键字)唯一确定一行.此时, ...

  5. Linux编程 8 (挂载mount,查看磁盘df du,搜索grep,压缩zgip,归档tar)

    一. 挂载存储媒体 linux文件系统将所有的磁盘都并入一个虚拟目录下,当使用新的存储媒体之前,需要把它放到虚拟目录下,这项工作称为挂载(mounting) 1.1 mount 命令 在linux上用 ...

  6. ACM学习<二>

    穷举算法思想:     一句话:就是从所有可能的情况,搜索出正确的答案. 步骤:     1.对于一种可能的情况,计算其结果.     2.判断结果是否满足,YES计算下一个,no继续步骤1,然后判断 ...

  7. git reset命令使用

    版本回退 当前有三个commit提交版本commit1commit2commit3Git必须知道当前版本是哪个版本,在Git中,用HEAD表示当前版本上一个版本是HEAD^,上上一个版本是HEAD^^ ...

  8. Enumerable转换为DataTable

    今天在项目组公共类库中发现一个 Enumerable类型转换为DataTable,写的挺精简的,拿出来跟大家共享一下. using System; using System.Collections.G ...

  9. SVM笔记

    1.前言 SVM(Support Vector Machine)是一种寻求最大分类间隔的机器学习方法,广泛应用于各个领域,许多人把SVM当做首选方法,它也被称之为最优分类器,这是为什么呢?这篇文章将系 ...

  10. 关于Class对象、类加载机制、虚拟机运行时内存布局的全面解析和推测

    简介: 本文是对Java的类加载机制,Class对象,反射原理等相关概念的理解.验证和Java虚拟机中内存布局的一些推测.本文重点讲述了如何理解Class对象以及Class对象的作用. 欢迎探讨,如有 ...