1、java后台解析公众号网页用户的openid
公众号网页获取用户的code,传到接口
public static Map<String,Object> getOpenId(String code){
log.info("解析code>>>>>>>>>>>>>>>>>" + code);
Map<String, Object> map = new HashMap<>();
if(code.length() == 0){
return map;
}
String openid = "";
String access_token = "";
String xml = HttpUtils.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", "appid="+APP_ID+"&secret="+AppSecret+"&code=" + code + "&grant_type=authorization_code");
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 =new JSONObject();
jsonObject1 = jsonObject.parseObject(xml);
log.info("获取openId>>>>>xml>>>>>"+xml);
openid = jsonObject1.getString("openid");
access_token = jsonObject1.getString("access_token");
System.out.println(jsonObject1.getString("openid"));
log.info("获取到的openId>>>>" + openid + ">>>>date>>>" + DateUtils.getTime());
map.put("openId",openid);
map.put("access_token",access_token);
return map;
}
public static String sendGet(String url, String param)
{
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try
{
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (Exception ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}