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

java_lover發表於2015-02-27

關於snsapi_userinfo網頁授權的說明

以snsapi_userinfo為scope發起的網頁授權,是用來獲取使用者的基本資訊的。但這種授權需要使用者手動同意,並且由於使用者同意過,所以無須關注,就可在授權後獲取該使用者的基本資訊。

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



具體程式碼如下:(程式碼參考部落格: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;
/**
 * Oauth2Servlet
 *
 * @author admin 
 * @date 2015-2-27 下午04:32:55
 */
public class Oauth2Servlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    /**
     * snsapi_userinfo為scope發起的網頁授權<br/>
     * 是用來獲取使用者的基本資訊的。但這種授權需要使用者手動同意,並且由於使用者同意過,所以無須關注,就可在授權後獲取該使用者的基本資訊。
     */
    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";
        
        String get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

        // 將請求、響應的編碼均設定為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 access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        get_userinfo = get_userinfo.replace("ACCESS_TOKEN", access_token);
        get_userinfo = get_userinfo.replace("OPENID", openid);

        String userInfoJson = HttpsGetUtil.doHttpsGetJson(get_userinfo);

        JSONObject userInfoJO = JSONObject.fromObject(userInfoJson);

        String user_openid = userInfoJO.getString("openid");
        String user_nickname = userInfoJO.getString("nickname");
        String user_sex = userInfoJO.getString("sex");
        String user_province = userInfoJO.getString("province");
        String user_city = userInfoJO.getString("city");
        String user_country = userInfoJO.getString("country");
        String user_headimgurl = userInfoJO.getString("headimgurl");

        // UserInfo_weixin userInfo=new UserInfo_weixin(user_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:" + user_openid + "\n\n");
        out.println("nickname:" + user_nickname + "\n\n");
        out.println("sex:" + user_sex + "\n\n");
        out.println("province:" + user_province + "\n\n");
        out.println("city:" + user_city + "\n\n");
        out.println("country:" + user_country + "\n\n");
        out.println("<img src=/" + user_headimgurl + "/");
        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;
    }
}

 

 

 

相關文章