微信公众平台--网页授权获取用户基本信息(snsapi_userinfo方式)

时间:2024-02-18 10:25: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;
    }
}