利用servlet 实现JAVAWeb访问微信OAuth2.0认证,获取用户信息的实例

来源:互联网 发布:安卓应用知乎 编辑:程序博客网 时间:2024/05/20 02:26

先让我吐槽一下:

也不知道是本人技术有限还是各路大神故弄玄虚,网上的实例内容很少,关键代码都不公布,最后还是自己东平西凑搞定了这个难题,现在将提供一份完整的实例出来,供初学者学习。

回归正题:

首先讲解一下OAuth2.0方面的技术问题

我们要想获取微信用户信息,需要通过微信官方OAuth2.0认证,访问的办法就是向微信服务器发送一条URL。
这个URL格式如下:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf370f557c5df3a88&redirect_uri=http://xueqi1115.oicp.net/GW/servlet/OAuth2Servlet&response_type=code&scope=snsapi_base&state=99#wechat_redirect
里面需要修改的内容是appid 和 redirect_uri ,上面这个例子是我自己的appid 和redirect_uri.
appid为你自己的微信官方给出的唯一appid信息,不用多说
redirect_url 是你向服务器发送请求后,需要接受服务器返回消息的serlet地址。
其他不需要变动
另外需要强调的一点是,在微信公众平台管理菜单中找到接口权限菜单,打开后找到图所示权限接口:

点击修改按钮,填写你的真实有效域名地址。例如我们平常访问http://www.baidu.com,那么你要填写的就是去掉http://协议头的www.baidu.com就行。我的域名是xueqi1115.oicp.net。
接下来我们继续在微信公众平台管理菜单中找到自动以菜单,创建一个菜单项,名字随便起,但是要使用网页跳转的方式,其跳转的地址就是我最上面给出的那个URL

java的具体实现

首先创建一个servlet,直接上代码了:
package org.weixin.servlet;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.json.JSONException;import org.json.JSONObject;public class OAuth2Servlet extends HttpServlet {private static String APPID = "wxfxxxxxxxxxxxxx";//这个是你服务号appid,和URL里面的appid是一个意思private static String APPSECRET = "xxxxxxxxxxxxxxxxxxxxx"; //这个是你服务号的app秘钥private static String ACCESS_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code"; //这个是请求获取用户信息的URLpublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("来自微信的请求...");request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");String code = request.getParameter("code");//获取OAuth2.0请求后,服务器返回的code内容,这个code在接下来向微信服务请求用户信息的时候要用到System.out.println(code);String requestUrlString = ACCESS_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET).replace("CODE", code);//将请求用户的URL中的///参数替换成真正的内容System.out.println(requestUrlString);URL url = new URL(requestUrlString);  //创建url连接HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //打开连接urlConnection.setDoOutput(true);urlConnection.setDoInput(true);urlConnection.setRequestMethod("GET");urlConnection.setUseCaches(false);urlConnection.connect();BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));StringBuffer buffer = new StringBuffer();<span style="font-family: Arial, Helvetica, sans-serif;">//存储服务器返回的信息</span>String line = ""; String openid = "";   //用来接收用户的appidwhile ((line = reader.readLine()) != null) {buffer.append(line);}String result = buffer.toString();System.out.println(result);try {JSONObject resultObject = new JSONObject(result); //将服务器返回的字符串转换成json格式openid = resultObject.getString("openid");  //获取得到用户appid} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}request.setAttribute("code", code);request.setAttribute("openid", openid);RequestDispatcher res = request.getRequestDispatcher("../weixin_index.jsp");  //跳转页面res.forward(request, response);}}
下面是跳转的jsp页面代码 ,非常简单
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'weixin_index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   这是来自网页的显示:${requestScope.code }</br>   用户id:${requestScope.openid }  </body></html>



1 0
原创粉丝点击