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"

代码可以直接运行

post python 微信 urllib

没福利会死星人 9 years, 8 months ago

建议使用requests库来做

西蒙·贝尔萌特 answered 9 years, 8 months ago

Your Answer