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

来源:互联网 发布:程序员转行能干什么 编辑:程序博客网 时间:2024/05/29 23:48


首先讲解一下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,直接上代码了:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package org.weixin.servlet;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import javax.servlet.RequestDispatcher;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import org.json.JSONException;  
  16. import org.json.JSONObject;  
  17.   
  18. public class OAuth2Servlet extends HttpServlet {  
  19.       
  20.     private static String APPID = "wxfxxxxxxxxxxxxx";//这个是你服务号appid,和URL里面的appid是一个意思  
  21.     private static String APPSECRET = "xxxxxxxxxxxxxxxxxxxxx"//这个是你服务号的app秘钥  
  22.     private static String ACCESS_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code"; //这个是请求获取用户信息的URL  
  23.   
  24.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  25.             throws ServletException, IOException {  
  26.         System.out.println("来自微信的请求...");  
  27.         request.setCharacterEncoding("UTF-8");  
  28.         response.setCharacterEncoding("UTF-8");  
  29.         String code = request.getParameter("code");//获取OAuth2.0请求后,服务器返回的code内容,这个code在接下来向微信服务请求用户信息的时候要用到  
  30.         System.out.println(code);  
  31.         String requestUrlString = ACCESS_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET).replace("CODE", code);//将请求用户的URL中的///参数替换成真正的内容  
  32.         System.out.println(requestUrlString);  
  33.         URL url = new URL(requestUrlString);  //创建url连接  
  34.         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //打开连接  
  35.         urlConnection.setDoOutput(true);  
  36.         urlConnection.setDoInput(true);  
  37.         urlConnection.setRequestMethod("GET");  
  38.         urlConnection.setUseCaches(false);  
  39.         urlConnection.connect();  
  40.         BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));  
  41.         StringBuffer buffer = new StringBuffer();<span style="font-family: Arial, Helvetica, sans-serif;">//存储服务器返回的信息</span>  
  42.         String line = "";   
  43.         String openid = "";   //用来接收用户的appid  
  44.         while ((line = reader.readLine()) != null) {  
  45.             buffer.append(line);  
  46.         }  
  47.         String result = buffer.toString();  
  48.         System.out.println(result);  
  49.         try {  
  50.             JSONObject resultObject = new JSONObject(result); //将服务器返回的字符串转换成json格式  
  51.             openid = resultObject.getString("openid");  //获取得到用户appid  
  52.         } catch (JSONException e) {  
  53.             // TODO Auto-generated catch block  
  54.             e.printStackTrace();  
  55.         }  
  56.         request.setAttribute("code", code);  
  57.         request.setAttribute("openid", openid);  
  58.         RequestDispatcher res = request.getRequestDispatcher("../weixin_index.jsp");  //跳转页面  
  59.         res.forward(request, response);  
  60.     }  
  61.       
  62.   
  63.   
  64. }  
下面是跳转的jsp页面代码 ,非常简单
[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'weixin_index.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.    这是来自网页的显示:${requestScope.code }</br>  
  27.    用户id:${requestScope.openid }  
  28.   </body>  
  29. </html>  
0 0