微信公眾平臺--網頁授權獲取使用者基本資訊(snsapi_base方式)

java_lover發表於2015-02-27

關於snsapi_base網頁授權的說明

以snsapi_base為scope發起的網頁授權,是用來獲取進入頁面的使用者的openid的,並且是靜默授權並自動跳轉到回撥頁的。使用者感知的就是直接進入了回撥頁(往往是業務頁面)

微信開啟連結(https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx48414ee14f7d7158
&redirect_uri=http://test.cn/testWx//servlet/Oauth2Servlet&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect)
即可看到效果,效果截圖如下:
只列印了 openid。

具體程式碼如下:(程式碼參考部落格:http://www.cnblogs.com/zyw-205520/p/3581088.html)
 
Oauth2Servlet.java
package com.payroll.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.payroll.wx.util.CommendDef;
import com.payroll.wx.util.HttpsGetUtil;

public class CopyOfOauth2Servlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //靜默授權
        String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid="
                + CommendDef.AppId
                + "&secret="
                + CommendDef.AppSecret
                + "&code=CODE&grant_type=authorization_code";

        // 將請求、響應的編碼均設定為UTF-8(防止中文亂碼)
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String code = request.getParameter("code");

        System.out.println("******************code=" + code);

        get_access_token_url = get_access_token_url.replace("CODE", code);

        String json = HttpsGetUtil.doHttpsGetJson(get_access_token_url);

        JSONObject jsonObject = JSONObject.fromObject(json);
        String openid = jsonObject.getString("openid");

        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method \n");
        out.println("openid:" + openid + "\n\n");
        out.println(">");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

}

HttpsGetUtil.java
package com.payroll.wx.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpsGetUtil
{

    public static String doHttpsGetJson(String Url)
    {
        String message = "";
        try
        {
            System.out.println("doHttpsGetJson");//TODO:dd
            URL urlGet = new URL(Url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); 
            http.setRequestMethod("GET");      //必須是get方式請求    24           
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
            http.setDoOutput(true);  
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//連線超時30秒28     
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //讀取超時30秒29 30       
            http.connect();
            InputStream is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            message=new String(jsonBytes,"UTF-8");
        } 
        catch (MalformedURLException e)
        {
              e.printStackTrace();
          }
        catch (IOException e)
          {
              e.printStackTrace();
          } 
        return message;
    }
}

 

 

相關文章