实现微信授权登录
首先按照官方文档的步骤
2 第二步:通过code换取网页授权access_token
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
@WebServlet("/wxLogin") public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String backUrl = "http://url/WeixinTest/callBack"; String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + "appid="+AuthUtil.APPID + "&redirect_uri="+URLEncoder.encode(backUrl) + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect"; System.out.println("================"); response.sendRedirect(url); } }
@WebServlet("/callBack") public class CallBackServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("code"); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid="+AuthUtil.APPID + "&secret="+AuthUtil.APPSECET + "&code="+code + "&grant_type=authorization_code"; JSONObject jsonObject = AuthUtil.doGetJson(url); String openid = jsonObject.getString("openid"); String token = jsonObject.getString("access_token"); String tourl = "https://api.weixin.qq.com/sns/userinfo?" + "access_token="+token + "&openid="+openid + "&lang=zh_CN"; JSONObject userInfo = AuthUtil.doGetJson(tourl); System.out.println(userInfo); } }
包装的util
public class AuthUtil { public static final String APPID = "id"; public static final String APPSECET = "secet"; public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException{ JSONObject jsonObject = null; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(result); } httpGet.releaseConnection(); return jsonObject; } }
大家觉得不错的话可以支持一下