微信授权(二) 获取openid

一: 获取openid

   阅读微信授权(一) 后,通过访问https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxabc670e3c404adf9&redirect_uri=http%3A%2F%2F1864rg4803.imwork.net%2F%2FweChat%2FgetCode&response_type=code&scope=snsapi_userinfo&state=students-photo.html 调回java方法

  我写的方法名是/weChat/getCode,下面上代码:

@Controller
@RequestMapping(value = "/weChat")
public class WeChatController {
	@RequestMapping(value = "/getCode", produces = "text/html;charset=UTF-8")
	public String resultCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = null;
		code = request.getParameter("code");// 用户授权码
		String state = request.getParameter("state");// 
	
		// 通过code获取网页授权access_token
		AuthToken authToken = WebChatUtil.getTokenByAuthCode(code);

		String openId = authToken.getOpenid();
		System.out.println("openid " + openId);

        String url="重定向到H5页面?openid="+openId;
		return url;
	}
}

  2.WebChatUtil:

package com.web.wx.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.codehaus.jackson.map.ObjectMapper;

import com.web.common.AuthToken;
import com.web.common.WxConstant;



public class WebChatUtil {
	/**
	 * 扩展xstream,使其支持name带有"_"的节点
	 */
	// public static XStream xStream = new XStream(new DomDriver("UTF-8", new
	// XmlFriendlyNameCoder("-_", "_")));
	private static ObjectMapper jsonObjectMapper = new ObjectMapper();

	/**
	 * 根据code获取微信授权access_token
	 */
	public static AuthToken getTokenByAuthCode(String code) {
		// public static AuthToken getTokenByAuthCode() {
		AuthToken authToken = null;
		StringBuilder json = new StringBuilder();
		try {
			URL url = new URL(WxConstant.Authtoken_URL(code));
			URLConnection uc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
				System.out.println("遍历json" + json.toString());
			}
			in.close();
			// 将json字符串转成javaBean
			authToken = jsonToEntity(json.toString(), AuthToken.class);
		} catch (IOException ex) {
			System.out.println("获取access_token异常");
		}
		return authToken;
	}

	/**
	 * Json字符转Java实体
	 * 
	 * @param jsonString
	 *            Json字符串
	 * @param entityType
	 *            实体类型
	 * @return default null,表示转换失败
	 */
	public static  T jsonToEntity(String jsonString, Class entityType) {
		T entity = null;

		try {
			entity = jsonObjectMapper.readValue(jsonString, entityType);
		} catch (Exception e) {
			System.out.println("Json转换异常");
		}

		return entity;
	}

}

 3.WxConstant:

package com.web.common;

public class WxConstant {
	
    /**
	 * 公众号AppId wx9dfff98fb16feb04
	 */
	public static final String APP_ID = "AppId";

	/**
	 * 公众号AppSecret defc6832db583495c9101a961836fdfc
	 */
	public static final String APP_SECRET = "AppSecret ";

	/**
	 * 返回成功字符串
	 */
	public static final String RETURN_SUCCESS = "SUCCESS";

	/**
	 * 支付地址(包涵回调地址)
	 */
	static String redirectUrl = "";
	public static final String PAY_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri=" + redirectUrl
			+ "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

	/**
	 * 通过code获取授权access_token的URL
	 */
	public static String Authtoken_URL(String code) {
		StringBuffer url = new StringBuffer();
		// api.weixin.qq.com 10.10.208.11:8033
		url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
		url.append(WxConstant.APP_ID);
		url.append("&secret=");
		url.append(WxConstant.APP_SECRET);
		url.append("&code=");
		url.append(code);
		url.append("&grant_type=authorization_code");
		return url.toString();
	}
}

即可授权后拿到openId

你可能感兴趣的:(JAVA)