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

15 篇文章 0 订阅

先让我吐槽一下:

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

回归正题:

首先讲解一下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"; //这个是请求获取用户信息的URL

	public 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 = "";   //用来接收用户的appid
		while ((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 block
			e.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>



  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xq30397022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值