如何在urllib2中post中文(Python)
sendmsg={"touser":"mr-zhoong","toparty":"1","totag":"1","msgtype":"text","agentid":"1...
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
在sendmsg的content中 如果有中文,会报错:
"errcode":40033,"errmsg":"invalid charset. please check your request, if include \\uxxxx will create fail!"
当前无中文,返回:"errcode":0,"errmsg":"ok"
试过:data = json.dumps(sendmsg, ensure_ascii=False).encode('utf8') 等都不可以 展开
"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
在sendmsg的content中 如果有中文,会报错:
"errcode":40033,"errmsg":"invalid charset. please check your request, if include \\uxxxx will create fail!"
当前无中文,返回:"errcode":0,"errmsg":"ok"
试过:data = json.dumps(sendmsg, ensure_ascii=False).encode('utf8') 等都不可以 展开
1个回答
2015-04-10
展开全部
那个参数字符串可能会是中文,就直接param_text.encode('utf-8'),不要等到最后再集中编码。
追问
param_text = u"你好"
sendmsg = {"touser": "mr-zhoong", "toparty": "1", "totag": "1", "msgtype": "text", "agentid": "1", "text": {"content": param_text.encode('utf-8')}, "safe": "0"}
是这样吗?还是提示出错
追答
多情况条件,处理相对复杂一点,给你贴一个别人写的的参数编码函数,你研究一下,或者直接用:
def _encode_params(**kw):
'''
Do url-encode parameters
>>> _encode_params(a=1, b='R&D')
'a=1&b=R%26D'
>>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123])
'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
'''
#return urllib.urlencode(kw)
def _encode(L, k, v):
if isinstance(v, unicode):
L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))
elif isinstance(v, str):
L.append('%s=%s' % (k, urllib.quote(v)))
elif isinstance(v, collections.Iterable):
for x in v:
_encode(L, k, x)
else:
L.append('%s=%s' % (k, urllib.quote(str(v))))
args = []
for k, v in kw.iteritems():
_encode(args, k, v)
return '&'.join(args)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询