1. 程式人生 > >利用servlet 實現JAVAWeb訪問微信OAuth2.0認證,獲取使用者資訊的例項

利用servlet 實現JAVAWeb訪問微信OAuth2.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>