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

来源:互联网 发布:win8没有windows图标 编辑:程序博客网 时间:2024/06/02 04:42

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

最初我的编码方式如下:

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如期打印,而且客户端成功收到返回结果。


原创粉丝点击