获取微信用户信息出现乱码
在绑定用户微信时,需要从微信获取用户信息,此处容易出现乱码。
JSONObject jo = this.getAccessTokenOpenid(code); StringBuilder sb = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?access_token="); sb.append(jo.getString("access_token")); sb.append("&openid=").append(jo.getString("openid")).append("&lang=zh_CN"); HttpMethod method = new PostMethod(sb.toString()); HttpClient httpclient = new HttpClient(); httpclient.executeMethod(method); String result = new String(method.getResponseBody(), "utf-8"); // String result = method.getResponseBodyAsString();
System.out.println("getWeiXinUserInfo result = " + result); JSONObject userInfo = JSON.parseObject(result, JSONObject.class);
将 String result = method.getResponseBodyAsString();
换成 String result = new String(method.getResponseBody(), "utf-8");
即可。
method.getResponseBodyAsString():
Returns the response body of the HTTP method, if any, as a String
. If response body is not available or cannot be read, null is returned. The raw bytes in the body are converted to a String
using the character encoding specified in the response's Content-Type header, or ISO-8859-1 if the response did not specify a character set.
Note that this method does not propagate I/O exceptions. If an error occurs while reading the body, null
will be returned.
而:new String(method.getResponseBody(), "utf-8")
将 method.getResponseBody() 返回的原生字节用指定的 utf-8 编码,编码成String。因为微信的返回值就是采用的utf-8编码。
运行结果:
没有乱码出现。
相关文章
- WordPress实现关注微信公众号回复关键字获取验证码查看网站隐藏内容
- 微信小程序 - 获取所在位置(省、市、区)
- 微信小程序 - 获取当前日期时间(函数封装)
- 微信定位功能结合百度地图获取用户城市
- 微信小程序登陆并获取用户信息
- 微信小程序 跳坑
- 微信公众号网页授权登录获取用户基本信息
- Python+ITchart实现微信机器人对指定的朋友和群自动回复
- Java中的微信支付(2):API V3 微信平台证书的获取与刷新
- 用c#开发微信(2)扫描二维码,用户授权后获取用户基本信息 (源码下载)
- 微信小程序~页面跳转
- 微信小程序~获取网络状态
- 微信聊天小程序——(二、账号的注册与登录)
- 微信小程序日历插件对比
- 微信小程序 云调用获取微信步数
- 微信小程序无法获取UnionId的情况及处理
- 微信公众号获取openid
- 在微信小程序上做一个「博客园年度总结」:解决前端获取接口数据太慢的一种思路
- 开发一个微信小程序(8):查询天气-获取用户所在位置,查询当前城市天气