python 使用urllib2进行https请求时出现'ascii' codec can't decode byte 0xe9 错误

最近在开发公众号,其中进行到菜单开发时,使用urllib模块通过官方提供的https链接进行创建菜单操作:

def create(self, postData, accessToken):
    postUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % accessToken
    if isinstance(postData, unicode):
        postData = postData.encode('utf-8')
    urlResp = urllib.urlopen(url=postUrl, data=postData)
    print urlResp.read()
调用create()进行创建操作之后,出现ssl:unknown错误提示,查找原因,说是http和https运行不能共用一个端口。有点不明觉厉。。。这个时候我并没有运行http请求啊,不应该存在端口冲突啊。百思不得其解,所以,我就换个路径,把urllib换成了urllib2试了试。

def create(self, postData, accessToken):
    postUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % accessToken
    if isinstance(postData, unicode):
        postData = postData.encode('utf-8')
    urlResp = urllib2.urlopen(postUrl, data=postData)
    print urlResp.read()
运行之后发现,好像有那没点不一样了,最起码错误类型不一样了,ssl错误不见了,变成了'ascii' codec can't decode byte 0xe9 in position 100: ordinal not in range(128)。这个错误算是比较常见的python编码错误了,python初始默认编码是ascii编码,在与其他编码进行转换时,中间采用unicode编码,就在这个过程中出现了错误:unicode编码最大只有128位,所以当尝试将ascii编码转换成unicode编码时出现了超出范围,不能编码的错误。知道了原因,就可以修改了。

在代码开始添加如下一段代码,作用是设置python默认编码为utf-8编码格式。

import sys
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)
这样就不会存在转换编码格式错误的问题了。

这个方法仅仅针对单个文件起着作用,还可以在python安装文件的site-packages/目录下添加一个sitecustomize.py文件,内容如下:

import sys
sys.setdefaultencoding(defaultencoding)

这个针对所有文件都有效。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值