jsapi_ticket使用微信JS-SDK会用到。
只是做个笔记,代码写的很乱,懒得整理
CommonUtil.java
package com.qz.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.Properties;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
/**
* 用于获取access_token的工具类
*
* @author QZ
* @date 2018.03.29
*
*/
public class CommonUtil {
private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 发送http请求
*
* @param requestUrl
* @param requestMethod
* @param outputStr
* @return JSONObject(通过JSONObject.get(key)的方式获取JSON对的属性值)
*/
public static JSONObject httpsRequest(String requestUrl,
String requestMethod, String outputStr) {
JSONObject jsonObject = null;
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);
// 当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();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("http请求异常:{}", e);
}
//
return jsonObject;
}
/**
* 获取acess_token并保存,并判断access_token是否过期
* @return
*/
public static String getAccessToken() {
// 保存access_token文件名字
String FileName = "wxAccessToken.properties";
try {
// 从文件中获取token值及时间
Properties properties = new Properties();// 属性集合对象
// 获取文件流
InputStream fis = CommonUtil.class.getClassLoader()
.getResourceAsStream(FileName);
// 将属性文件流装载到Properties对象中
properties.load(fis);
fis.close();
// 获取Appid,Appsecret
String appID = properties.getProperty("APPID");
String appSecret = properties.getProperty("APPSECRET");
String access_token = properties.getProperty("access_token");
String expires_in = properties.getProperty("expires_in");
String last_time = properties.getProperty("last_time");
int int_expires_in = 0;
long long_last_time = 0;
try {
int_expires_in = Integer.parseInt(expires_in);
long_last_time = Long.parseLong(last_time);
} catch (Exception e) {
e.printStackTrace();
}
// 得到当前时间
long current_time = System.currentTimeMillis();
// 每次调用,判断expires_in是否过期,如果token时间超时,重复获取,
if ((current_time - long_last_time) / 1000 >= int_expires_in) {
// 获取access_token
String requestUrl = ACCESS_TOKEN_URL.replace("APPID", appID)
.replace("APPSECRET", appSecret);
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
String j_access_token = (String) jsonObject.get("access_token");
String j_expires_in = (String) jsonObject.get("expires_in").toString();
// 保存access_token
if (j_access_token != null && j_expires_in != null) {
properties.setProperty("access_token", j_access_token);
properties.setProperty("expires_in", j_expires_in);
properties.setProperty("last_time",
System.currentTimeMillis() + "");
URL url_ = CommonUtil.class.getClassLoader()
.getResource(FileName);
FileOutputStream fos = new FileOutputStream(new File(
url_.toURI()));
properties.store(fos, null);
fos.close();// 关闭流
}
return j_access_token;
} else {
return access_token;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取jsApiTicket
* @param access_token
* @return
*/
public static String getJsApiTicket(String access_token){
// 保存jsapi_ticket文件名字
String FileName = "jsapi_ticket.properties";
try {
//从文件中获取jsapi_ticket值及时间
Properties properties=new Properties();
//获取文件流
InputStream fis = CommonUtil.class.getClassLoader()
.getResourceAsStream(FileName);
//将属性文件流装载到Properties对象中
properties.load(fis);
fis.close();
//获取jsapi_ticket、last_time、expires_in
String jsapi_ticket = properties.getProperty("jsapi_ticket");
String expires_in = properties.getProperty("expires_in");
String last_time = properties.getProperty("last_time");
int int_expires_in=0;
long long_last_time=0;
int_expires_in = Integer.parseInt(expires_in);
long_last_time = Long.parseLong(last_time);
//得到当前系统时间擢
/*该方法的作用是返回当前的计算机时间,
* 时间的表达格式为当前计算机时间和GMT时间(格林威治时间)
* 1970年1月1号0时0分0秒所差的毫秒数。*/
long current_time = System.currentTimeMillis();
// 每次调用,判断expires_in是否过期,如果ticket时间超时,重复获取,
if ((current_time-long_last_time)/1000>=int_expires_in) {
String jsapi_ticketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
+ access_token + "&type=jsapi";
JSONObject jsonObject = httpsRequest(jsapi_ticketURL, "GET", null);
String jsapi_ticket_new = (String)jsonObject.getString("ticket");
String expires_in_new=(String)jsonObject.get("expires_in").toString();
//保存jsapi_ticke和expires_in
if (jsapi_ticket_new != null&&expires_in_new!=null) {
properties.setProperty("jsapi_ticket", jsapi_ticket_new);
properties.setProperty("expires_in", expires_in_new);
properties.setProperty("last_time", System.currentTimeMillis()+"");
URL url_ = CommonUtil.class.getClassLoader().getResource(
FileName);
FileOutputStream fos = new FileOutputStream(new File(
url_.toURI()));
properties.store(fos, null);
fos.close();// 关闭流
}
return jsapi_ticket_new;
}else {
return jsapi_ticket;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
wxAccessToken.properties
APPID= //自己的APPID
APPSECRET= //自己的APPSECRET
access_token=0
last_time=0
expires_in=7200
jsapi_ticket.properties
jsapi_ticket=0
last_time=0
expires_in=7200
毕业设计做微信公众号,这也是模仿别人的。写的很乱,时间赶也懒得整理了。