微信 开发 CommonUtil 获取token 及发送接收请求

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.UnsupportedEncodingException;

import java.net.ConnectException;

import java.net.URL;

import java.util.Date;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSocketFactory;

import javax.net.ssl.TrustManager;

import javax.servlet.http.HttpServletRequest;

import net.jeeshop.core.mobile.FrontContainer;

import net.jeeshop.mobile.services.front.account.bean.Account;

import net.jeeshop.mobile.services.front.systoken.bean.Token;

import net.sf.json.JSONException;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;

/**

 * 通用工具类

 * 

 * @author

 * 

 */

public class CommonUtil {

private static Logger log = LoggerFactory.getLogger(CommonUtil.class);

/**

* 发送https请求

* @param requestUrl

*            请求地址

* @param requestMethod

*            请求方式(GET、POST)

* @param outputStr

*            提交的数据

* @return 返回微信服务器响应的信息

*/

public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {

log.error("httpsRequest.requestUrl :{}", requestUrl);

try {

// 创建SSLContext对象,并使用我们指定的信任管理器初始化

TrustManager[] tm = { new MyX509TrustManager() };

SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

sslContext.init(null, tm, new java.security.SecureRandom());

// 从上述SSLContext对象中得到SSLSocketFactory对象

SSLSocketFactory ssf = sslContext.getSocketFactory();

URL url = new URL(requestUrl);

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

conn.setSSLSocketFactory(ssf);

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

// 设置请求方式(GET/POST)

conn.setRequestMethod(requestMethod);

conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");

// 当outputStr不为null时向输出流写数据

if (null != outputStr) {

OutputStream outputStream = conn.getOutputStream();

// 注意编码格式

outputStream.write(outputStr.getBytes("UTF-8"));

outputStream.close();

}

// 从输入流读取返回内容

InputStream inputStream = conn.getInputStream();

InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String str = null;

StringBuffer buffer = new StringBuffer();

while ((str = bufferedReader.readLine()) != null) {

buffer.append(str);

}

// 释放资源

bufferedReader.close();

inputStreamReader.close();

inputStream.close();

inputStream = null;

conn.disconnect();

log.error("httpsRequest 方法:{}", buffer.toString());

return buffer.toString();

} catch (ConnectException ce) {

log.error("连接超时:{}", ce);

} catch (Exception e) {

log.error("https请求异常:{}", e);

}

return null;

}

/**

* 获取接口访问凭证(不应该放到session内 需引以为戒,放数据库 或其他持久层模式) 基础支持 token

* @param appid

*            凭证

* @param appsecret

*            密钥

* @return

*/

public static Token getToken(String openid, String appid, String appsecret, HttpServletRequest request) {

Token token = null;

if (request != null && request.getSession() != null) {

token = (Token) request.getSession().getAttribute(openid + "token");

}

String requestUrl = ConfigUtil.BASE_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", appsecret);

if (null == token || ((new Date().getTime() - token.getTime()) / 1000) > 7150) {

// 发起GET请求获取凭证

JSONObject jsonObject = JSONObject.fromObject(httpsRequest(requestUrl, "GET", null));

log.error("获取getToken jsonObject====================", jsonObject.toString());

if (null != jsonObject) {

try {

token = new Token();

token.setAccessToken(jsonObject.getString("access_token"));

token.setExpiresIn(jsonObject.getInt("expires_in"));

token.setTime(new Date().getTime());

if (request != null && request.getSession() != null) {

request.getSession().setAttribute(openid + "token", token);

}

} catch (JSONException e) {

token = null;

// 获取token失败

log.error("获取基础支持token失败 errcode:{} errmsg:{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));

}

}

}

return token;

}

/**

* 获取接口访问凭证(不应该放到session内 需引以为戒,放数据库 或其他持久层模式) 基础支持 token

* @param appid

*            凭证

* @param appsecret

*            密钥

* @return

*/

public static Token getToken(String openid,HttpServletRequest request) {

Token token = null;

String requestUrl = ConfigUtil.BASE_TOKEN_URL.replace("APPID", ConfigUtil.APPID).replace("APPSECRET", ConfigUtil.APP_SECRECT);

// 发起GET请求获取凭证

JSONObject jsonObject = JSONObject.fromObject(httpsRequest(requestUrl, "GET", null));

log.error("不经过session 直接获取getToken jsonObject====================", jsonObject.toString());

if (null != jsonObject) {

try {

token = new Token();

token.setAccessToken(jsonObject.getString("access_token"));

token.setExpiresIn(jsonObject.getInt("expires_in"));

token.setTime(new Date().getTime());

if (request != null && request.getSession() != null) {

request.getSession().setAttribute(openid + "token", token);

}

} catch (JSONException e) {

token = null;

// 获取token失败

log.error("不经过session 直接获取基础支持token失败 errcode:{} errmsg:{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));

}

}

return token;

}

/**

* 通过code获取token

* @param appid

*            凭证

* @param appsecret

*            密钥

* @return

*/

public static Token getOAUTH2(String appid, String appsecret, String code, HttpServletRequest request) {

log.error("通过code获取token getOAUTH2 start=================================");

Token token = null;

if (request.getSession() != null) {

token = (Token) request.getSession().getAttribute(appid + "token");

}

String requestUrl = ConfigUtil.TOKEN_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);

if (null == token || ((new Date().getTime() - token.getTime()) / 1000) > 7150) {

// 发起GET请求获取凭证

JSONObject jsonObject = JSONObject.fromObject(httpsRequest(requestUrl, "GET", null));

log.error("获取token jsonObject====================", jsonObject.toString());

if (null != jsonObject) {

try {

token = new Token();

token.setAccessToken(jsonObject.getString("access_token"));

log.error("获取token access_token:{}", jsonObject.getString("access_token"));

token.setOpenId(jsonObject.getString("openid"));

log.error("获取token openId:{}", jsonObject.getString("openid"));

token.setRefeshToken(jsonObject.getString("refresh_token"));

log.error("获取token refeshToken:{}", jsonObject.getString("refresh_token"));

token.setScope(jsonObject.getString("scope"));

log.error("获取token scope:{}", jsonObject.getString("scope"));

token.setExpiresIn(jsonObject.getInt("expires_in"));

log.error("获取token expires_in:{}", jsonObject.getString("expires_in"));

// token.setUnionid(jsonObject.getString("unionid"));

// log.error("获取token unionid:{}",

// jsonObject.getString("unionid"));

token.setTime(new Date().getTime());

request.getSession().setAttribute(appid + "token", token);

} catch (JSONException e) {

token = null;

// 获取token失败

log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));

}

}

}

log.error("通过code获取token getOAUTH2 end=================================");

return token;

}

/**

* 获取用户信息

* @param openid

*            凭证

* @param access_token

*            密钥

* @return

*/

public static Account getUserinfo(String openid, String access_token) {

log.error("通过openid,access_token获取获取用户信息 getUserinfo start=================================");

HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

String requestUrl = ConfigUtil.TOKEN_URL.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);

// 发起GET请求获取凭证

JSONObject jsonObject = JSONObject.fromObject(httpsRequest(requestUrl, "GET", null));

log.error("获取getUserinfo jsonObject====================", jsonObject.toString());

Account account = null;

if (null != jsonObject) {

try {

account = new Account();

account.setAccessToken(jsonObject.getString("access_token"));

log.error("获取account access_token:{}", jsonObject.getString("access_token"));

account.setOpenId(jsonObject.getString("openid"));

log.error("获取account openId:{}", jsonObject.getString("openid"));

account.setNickname(jsonObject.getString("nickname"));

log.error("获取account nickname:{}", jsonObject.getString("nickname"));

account.setProvince(jsonObject.getString("province"));

log.error("获取account province:{}", jsonObject.getString("province"));

account.setCity(jsonObject.getString("city"));

log.error("获取account city:{}", jsonObject.getString("city"));

request.getSession().setAttribute(FrontContainer.USER_INFO, account);

} catch (JSONException e) {

account = null;

// 获取token失败

log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));

}

}

log.error("通过openid,access_token获取获取用户信息 getUserinfo end=================================");

return account;

}

// JAVA 获取完整URL 方法

public static String getRequestURL(HttpServletRequest request) {

log.error("获取请求信息 getRequestURL start=================================");

if (request == null) {

return "";

}

String url = "";

url = request.getContextPath();

url = url + request.getServletPath();

log.error("获取请求信息getRequestURL url=================================" + url);

if (!"".equals(request.getQueryString()) || request.getQueryString() != null) {

url = url + "?" + request.getQueryString();

}

/*

* java.util.Enumeration names = request.getParameterNames(); int i = 0;

* if (names != null) { while (names.hasMoreElements()) { String name =

* (String) names.nextElement(); if (i == 0) { url = url + "?"; } else {

* url = url + "&"; } i++;

* String value = request.getParameter(name); if (value == null) { value

* = ""; }

* url = url + name + "=" + value; try { //

* java.net.URLEncoder.encode(url, "ISO-8859"); } catch (Exception e) {

* e.printStackTrace(); } } }

*/

log.error("获取请求信息getRequestURL 参数 names=================================" + url);

try {

// String enUrl = java.net.URLEncoder.encode(url, "utf-8");

} catch (Exception ex) {

ex.printStackTrace();

}

log.error("获取请求信息getRequestURL end=================================");

return url;

}

/**

* 通过accessToken获取jsapi_ticket

* @param accessToken

* @param request

* @return

*/

public static Token getJsapi_ticket(String accessToken, HttpServletRequest request) {

Token token = null;

if (request.getSession() != null) {

token = (Token) request.getSession().getAttribute(accessToken + "ticket");

}

String requestUrl = ConfigUtil.JSAPI_TICKET.replace("ACCESS_TOKEN", accessToken);

if (null == token || ((new Date().getTime() - token.getTime()) / 1000) > 7150) {

// 发起GET请求获取凭证

JSONObject jsonObject = JSONObject.fromObject(httpsRequest(requestUrl, "GET", null));

log.error("获取token jsonObject====================", jsonObject.toString());

if (null != jsonObject) {

try {

token = new Token();

token.setAccessToken(jsonObject.getString("ticket"));

log.error("获取token ticket:{}", jsonObject.getString("ticket"));

token.setExpiresIn(jsonObject.getInt("expires_in"));

log.error("获取token expires_in:{}", jsonObject.getString("expires_in"));

token.setTime(new Date().getTime());

request.getSession().setAttribute(accessToken + "ticket", token);

} catch (JSONException e) {

token = null;

// 获取token失败

log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));

}

}

}

return token;

}

public static String urlEncodeUTF8(String source) {

String result = source;

try {

result = java.net.URLEncoder.encode(source, "utf-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return result;

}

}

相关推荐