python调用requests,默认body传text时候经常会因为格式报错。
我们可以通过传josn来避免报错,一种是json接收字典参数,或者json.loads把文本转字典。
下面是json接收字典
def send_data(self,msg): send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token() send_values = { "touser": self.TOUSER, "msgtype": "text", "agentid": self.AGENTID, "text": { "content": msg }, "safe": "0" } send_data = '{"msgtype": "text", "safe": "0", "agentid": %s, "touser": "%s", "text": {"content": "%s"}}' % ( self.AGENTID, self.TOUSER, msg) r = requests.post(send_url, json=send_values) # print r.content return r.content
另一个是用json.loads把文本转字典
def send_data(self,msg): send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token() send_values = { "touser": self.TOUSER, "msgtype": "text", "agentid": self.AGENTID, "text": { "content": msg }, "safe": "0" } send_data = '{"msgtype": "text", "safe": "0", "agentid": %s, "touser": "%s", "text": {"content": "%s"}}' % ( self.AGENTID, self.TOUSER, msg) r = requests.post(send_url, json=json.loads(send_data)) # print r.content return r.content