玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python urllib2 POST中文出错如何破解

response = urllib2.urlopen('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx4966bd9df888d05c&corpsecret=cIr3USJQLxp7wrMYFiaHKgjE8Az3Y9xTEqGQ3vrTBMoYguIepPkta-Ik5RsdMpqN')
res = response.read()
str = json.loads(res)
token = str['access_token']
url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+token
#print url
sendmsg = {"touser": "mr-zhoong", "toparty": "1", "totag": "1", "msgtype": "text", "agentid": "1",
          "text": {"content": u"你好This message is sent by co. ltd"}, "safe": "0"
          }
data = json.dumps(sendmsg)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page

返回:{"errcode":40033,"errmsg":"invalid charset. please check your request, if include \uxxxx will create fail!"}
尝试过:data = json.dumps(sendmsg, ensure_ascii=False).encode('utf8')
#data = json.dumps(sendmsg).encode('gbk')
均返回错误

其中 "text": {"content": u"This message is sent by co. ltd"} 是可以成功的,返回:"errcode":0,"errmsg":"ok"

代码可以直接运行

建议使用requests库来做

使用requests

headers = {'Content-Type': 'application/json', "charset": "utf-8"}
json_string = simplejson.dumps(data, ensure_ascii=False).encode('utf8')
wechat_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s'%self.get_access_token()
res = requests.post(wechat_url, data=json_string, headers=headers)

PS:使用requests的时候,参数使用data=,不要使用json=
这是我正在跑的代码。。。

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd18858.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月18日 - 21时12分17秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules