java微信发文字乱码_获取微信用户信息出现乱码

在绑定用户微信时,需要从微信获取用户信息,此处容易出现乱码。

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编码。

运行结果:

f374d7324f01839f2a8dc4fa6e8a2e52.png

没有乱码出现。

https://www.cnblogs.com/digdeep/category/639150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值