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

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

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

最初我的编码方式如下:

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

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

if recMsg.MsgType == 'location':location_X = recMsg.Location_Xlocation_Y = recMsg.Location_Ylabel = 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') + labelreplyMsg = reply.TextMsg(toUser, fromUser, content)return replyMsg.send()
果然,这次content如期打印,而且客户端成功收到返回结果。


发布者:admin,转转请注明出处:http://www.yc00.com/news/1691014233a486567.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信