3-3_ 公众号授权登录3

两种方式 

1.使用微信用户信息登录,无需注册和绑定

/WxAuth/src/com/wx/auth/servlet/CallBackServlet.java

package com.wx.auth.servlet;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import net.sf.json.JSONObject;
 
import com.wx.auth.util.AuthUtil;
 
@WebServlet("/callBack")
public class CallBackServlet extends HttpServlet{
 
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String code = req.getParameter("code");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID
				 + "&secret="+AuthUtil.APPSECRET
				 + "&code="+code
				 + "&grant_type=authorization_code";
		
		// 进行网络请求
		JSONObject jsonObject = AuthUtil.doGetJson(url);
		String openid = jsonObject.getString("openid");
		String token = jsonObject.getString("access_token");
		
		// 第四步:拉取用户信息(需scope为 snsapi_userinfo)
		//String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token
				 		+"&openid="+openid
				 		+"&lang=zh_CN";
		// 进行网络请求
		JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
		System.out.println("userInfo = "+userInfo);
		
//		resp.sendRedirect("http://www.baidu.com");
		//super.doGet(req, resp);
		
		
		// 1.使用微信用户信息登录,无需注册和绑定
		req.setAttribute("userInfo", userInfo);
		req.getRequestDispatcher("/index1.jsp").forward(req, resp);
		
	}
}

/WxAuth/WebContent/index1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
	<div>登录成功</div>
	<dir>用户昵称:${userInfo.nickname }</dir>
	<dir>用户头像:<img style="vertical-align:top;" width="100" src="${userInfo.headimgurl }"></dir>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/huanglianggu/article/details/81837416
3