zoukankan      html  css  js  c++  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编码。

    运行结果:

    没有乱码出现。

  • 相关阅读:
    修复mac os中的home键和end键
    利用numpy实现list降维
    string与StringBuilder的区别
    mysql 版本,mysqlconnectorjava, application.xml 的 driverclassname 的依赖关系
    linux下创建新用户新数据库并远程访问
    谷歌的JS编码规范链接
    sed命令之多行拷贝
    box2dWeb引擎案例
    SQL Server数据库镜像笔记
    团队项目系统设计
  • 原文地址:https://www.cnblogs.com/digdeep/p/4782422.html
Copyright © 2011-2022 走看看