Python urllib2 POST中文出错如何破解,,response = u


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 urlsendmsg = {"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=
这是我正在跑的代码。。。

编橙之家文章,

评论关闭