移动端获取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;
}