首页 > 上网技巧 > 电脑小技巧 > python({“errcode”:41011,”errmsg”:”miss...

python({“errcode”:41011,”errmsg”:”missing agentid”})

时间:2016-09-24 13:58 作者:QQ地带 我要评论

data = {   "touser": "monitor",   "toparty": "2",   "msgtype": "text",   "agentid": "1",   "text": {       "content": "test"   },   "safe":"0"}
 
post的数据格式我是这样写的 
用的python3,原来是这样进行格式化的
 
post_data=urllib.parse.urlencode(data).encode(encoding='UTF8');
 
得到的post数据格式是这样的
 
b'text=%7B%27content%27%3A+%27test%27%7D&touser=monitor&safe=0&toparty=2&msgtype=text&agentid=1'
 
提交后就报错了
 
{“errcode”:41011,”errmsg”:”missing agentid”}
 
百度查后,有网友说必须是json格式, 
然后我这样格式化
 
jdata = json.dumps(data).encode('UTF-8')
 
得到的数据是这样的
 
b'{"text": {"content": "test"}, "touser": "monitor", "safe": "0", "toparty": "2", "msgtype": "text", "agentid": "1"}'
 
这样就好了
 
上个完整版的
 
import http.cookiejar
import urllib.request
import json
class sendMessage():
    def __init__(self):
        self.cookieJar = http.cookiejar.LWPCookieJar() 
        opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookieJar))
        urllib.request.install_opener(opener)
    def sendMessage(self,user,message):
        getTokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx099c76afef3d1d6c&corpsecret=JDzPP2w7O1ijqV5WOrIHBB717Cii2Ln_ALjdvKIgb0UKU_mvNKqKmntP-nw28pHW"
        request = urllib.request.Request(getTokenUrl)
        request = urllib.request.urlopen(request)
        pageHtml = request.read().decode('UTF-8')
        token=pageHtml.split('"')[3]
        request.close()
        data = {   "touser": user,   "toparty": "2",   "msgtype": "text",   "agentid": "1",   "text": {       "content": message   },   "safe":"0"}
        #data = "{   'touser': 'monitor',   'toparty': '2',   'msgtype': 'text',   'agentid': 1,   'text': {       'content': 'test send message' },   'safe':'0'}"
 
        url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token
        header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}
        jdata = json.dumps(data).encode('UTF-8')
        request = urllib.request.Request(url,data=jdata,headers=header)
        request = urllib.request.urlopen(request)
        pageHtml = request.read().decode('UTF-8')
        print(pageHtml)
        request.close()
 
if __name__ == '__main__':
    up = sendMessage();
    up.sendMessage("monitor","test")

标签: Python
顶一下
(0)
0%
踩一下
(0)
0%

Google提供的广告