【微信】根據appid, secret, code獲取使用者openid(Java版)
阿新 • • 發佈:2021-06-24
【微信】根據appid, secret, code獲取使用者openid
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") + ""; } }