public static String weiXinLoginGetOpenId(String code) throws Exception {
URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?appid=xxx&secret=xxx&js_code=" + code);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
httpUrlConnection.setConnectTimeout(3000);
// 设置请求头属性参数
httpUrlConnection.setRequestProperty("charset", "UTF-8");
httpUrlConnection.setRequestProperty("accept", "application/json");
String response = "";// 响应内容
String status = "";// 响应状态
PrintWriter out = null;
BufferedReader in = null;
try{
httpUrlConnection.connect();
// 定义BufferedReader输入流来读取URL的响应数据
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
response += line;
}
// 获得URL的响应状态码
status = new Integer(httpUrlConnection.getResponseCode()).toString();
}catch(Exception e) {
logger.error("发送Get请求获取微信的openId出现错误", e);
}finally {
try {
if (out != null) { out.close();}
if (in != null) {in.close();}
} catch (Exception ex) {
logger.error("发送Get请求获取微信的openId出现错误", ex);
}
}
PageData typeValueData = new Gson().fromJson(response, PageData.class);
logger.info("响应状态:"+status);
logger.info("响应内容:"+response);
return typeValueData.getString("openid");
}
微信公众号开发后台通过code获取openId
最新推荐文章于 2024-06-23 23:51:42 发布