新手草鸟!!!!!!!!!!!!!!!
------解决思路----------------------
//appid,secret就是你在开放平台上申请的appid和secret.
//我这里就没有把我的填上了。另外你在申请的时候,需要要你填写一个回调域
//这个地址必须是外网可以访问的地址,你可以通过修改电脑的host配置文件,映射到你本地。
//你在页面上给个a标签先访问loginWechat.do,由于这是公司的项目,所有只能给你看这一部分。
//调试的时候,最好不要用firefox,因为firefox会将外网映射到本地的地址给屏蔽掉,所以一直会出现会先访问不到。
@RequestMapping("/loginWechat.do")
public void loginWeChat(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
try {
String state = request.getSession().getId();
int i = new Random().nextInt();
state = MD5Util.MD5(state + "" + i);
response.sendRedirect("https://open.weixin.qq.com/connect/qrconnect?appid=appid&redirect_uri=回调域/wechat/afterLoginWechat&response_type=code&scope=snsapi_login&state="
+ state + "#wechat_redirect");
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping("/afterLoginWechat")
public String AfterLoginRedirect(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr) {
response.setContentType("text/html;charset=utf-8");
String code = request.getParameter("code");
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
try {
// 通过code获取access_token
URL url = new URL(
"https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code="
+ code + "&grant_type=authorization_code");
conn = (HttpURLConnection) url.openConnection();
conn.connect();
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while (br.read() != -1) {
sb.append(br.readLine());
}
sb.insert(0, "{");
WechatDto wechatDto = JsonUtils.jsonToObject(sb.toString(), WechatDto.class);
// 通过access_token,openid获取用户信息
url = new URL("https://api.weixin.qq.com/sns/userinfo?access_token=" + wechatDto.getAccess_token()
+ "&openid=" + wechatDto.getOpenid());
conn = (HttpURLConnection) url.openConnection();
conn.connect();
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
sb = new StringBuilder();
while (br.read() != -1) {
sb.append(br.readLine());
}
} catch (MalformedURLException e) {
LOG.error(e.getMessage(), e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
try {
if (is != null)
is.close();
if (br != null)
br.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
return "redirect:/user/outRegisterAndLogin.html";
}