Springboot获取微信小程序openid
@Value("${appid}")
private String appId;
@Value("${appsecret}")
private String appSecret;
private String openId;
private String sessionKey;
@GetMapping("/index")
private String login(String code) {
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
try {
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
sessionKey = jsonObject.get("session_key")+"";
openId = jsonObject.get("openid")+"";
System.out.println("session_key=="+sessionKey);
System.out.println("openid=="+openId);
return resultString;
}