/**
* 通过code和小程序的appId,secretKey获取用户的openid、access_key等信息
* @author LCW
* @since 2020/11/2 21:39
**/
public class WxOpenIdUtils {
public static String login(String code, String appId, String secretKey) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response;
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secretKey + "&js_code=" + code + "&grant_type=authorization_code";
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
// 创建GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
// 解析json
return ((JSONObject) JSONObject.parse(result)).get("openid") + "";
}
}
通过code和小程序的appId,secretKey获取用户的openid、access_key等信息
最新推荐文章于 2022-05-27 08:50:49 发布