微信公众号开发之编码问题

在微信公众号开发阶段,服务器收到用户发送来的消息之后,会返回给用户一个文本消息,但是返回时却不能正确返回,下面以地理位置消息收发为例说明。

最初我的编码方式如下:

if recMsg.MsgType == 'location':
    location_X = recMsg.Location_X
    location_Y = recMsg.Location_Y
    label = recMsg.Label
    content = '您现在的位置是:\n经度:' + location_X + '\n纬度:' + location_Y + '\n地理位置信息:' + label
    print content
    replyMsg = reply.TextMsg(toUser, fromUser, content)
    return replyMsg.send()
运行结果出错,微信服务器并没有成功返回我的content数据。仔细看,代码逻辑并没有错误,为了标记,我在content下面打印了一下,再次运行发现,content并没有打印出来。说明这一行并没有成功生成content,想想肯定是编码问题了。然后我就参考官网实例,修改代码如下:

if recMsg.MsgType == 'location':
    location_X = recMsg.Location_X
    location_Y = recMsg.Location_Y
    label = recMsg.Label
    content = u'您现在的位置是:\n经度:'.encode('utf-8') + location_X + u'\n纬度:'.encode('utf-8') + location_Y + u'\n地理位置信息:'.encode('utf-8') + label
    print content
    replyMsg = reply.TextMsg(toUser, fromUser, content)
    return replyMsg.send()
想着,我已经把内容都用utf-8格式编码了,应该没问题了,但是运行之后发现,content还是不能如期打印,说明还是存在编码问题。之后,尝试着给label也进行一下utf-8编码,修改如下:

if recMsg.MsgType == 'location':
    location_X = recMsg.Location_X
    location_Y = recMsg.Location_Y
    label = recMsg.Label.encode('utf-8')
    content = u'您现在的位置是:\n经度:'.encode('utf-8') + location_X + u'\n纬度:'.encode(
        'utf-8') + location_Y + u'\n地理位置信息:'.encode('utf-8') + label
    replyMsg = reply.TextMsg(toUser, fromUser, content)
    return replyMsg.send()
果然,这次content如期打印,而且客户端成功收到返回结果。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值