h5微信获取用户信息及用户名乱码

移动端获取code 给接口,接口获取token,获取用户信息

 public Result h5UserInfo(String code){
        System.out.println("==============>输出code:"+code);

        /**获取token*/
        RestTemplate restTemplate = new RestTemplate();
        String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={secret" +
                "}&code" +
                "={code" +
                "}&grant_type=authorization_code";
        //设置请求参数
        Map<String, String> params = new HashMap<>(5);
        params.put("appId", WechatConstants.WECHAT_MP_APPID);
        params.put("secret", WechatConstants.WECHAT_MP_SECRET);
        params.put("code", code);
        String json = restTemplate.getForObject(access_token_url, String.class, params);
        JSONObject result = JSON.parseObject(json);

        System.out.println("========用户信息token"+result.toJSONString());

        /**获取用户信息*/
        String user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}" +
                "}&lang" +
                "=zh_CN";
        HashMap<String,String> map = new HashMap(4);
        map.put("access_token",result.getString("access_token"));
        map.put("openid",result.getString("openid"));


        RestTemplate userTemplate = new RestTemplate();
        // 创建一个StringHttpMessageConverter,并设置字符集为UTF-8
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        stringConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
        // 将StringHttpMessageConverter添加到RestTemplate的消息转换器列表中
        userTemplate.getMessageConverters().add(0, stringConverter);

        /**请求用户信息接口*/
        String userInfoJson = userTemplate.getForObject(user_info_url, String.class, map);
        JSONObject userInfo = JSON.parseObject(userInfoJson);

        System.out.println("========微信用户信息"+userInfo.toJSONString());
        return Result.ok();
    }

测试乱码数据Demo

  private boolean isISO88591(String str) {
        byte[] byteArr = str.getBytes(StandardCharsets.ISO_8859_1);
        String convertedStr = new String(byteArr, StandardCharsets.ISO_8859_1);
        // 比较原始字符串和转换后的字符串是否相等
        return str.equals(convertedStr);


    }

    private static String convertStrCharset(String str) {
        try {
            // 假设原始字符编码
            byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
            // 使用UTF-8重新编码为正常的字符串
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
//            log.warn("convertStrCharset failed,errorMsg:{}", e.getMessage());
        }
        return str;
    }
  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值