标题
获取access_token以及发消息给指定成员
access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token,access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
我的思路是通过txt文件保存access_token
1、创建 access_token.text文件
2、读取get_time
3、读取txt判断时间是否超过2个小时
4、超过则重写access_token.text文件
获取或重写txt文件中的access_token的工具类
public class AccessTokenUtil {
//文件地址
//按自己的路径来
private static final String filePath = System.getProperty("user.dir") + "/src/cn/scada/doc/access_token.txt";`//上次获取token的时间
public static Date getTime(String str) {
String get_time = str.substring(str.indexOf("=") + 1, str.length());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(get_time);
} catch (Exception c) {
System.out.println("获取时间出错了");
}
return date;
}
/*
* 读取txt文件
*/
public static String readText() {
//文件内容变量
String sTimg = "";//获取时间
String str = ""; //获取token值
try {
String encoding = "UTF-8";
File file = new File(filePath);
//考虑到编码格式
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
//读取的内容
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
sTimg = bufferedReader.readLine();
str = lineTxt;
}
//上次获取token的时间
Date getTime = getTime(sTimg);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
long m = new Date().getTime() - getTime.getTime();
//比较当前系统时间,如果超过7200秒就替换txt文本内容
if (m / 1000 > 7200) {
System.out.println("超时替换txt文件");
str = rebuildText();
}
read.close();
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
System.out.println("没有超时");
return str;
}
//重新生成文本内容
public static String rebuildText() {
try {
//获取新票据
String getToken = SendMsg.getSendMsgToken();
//清空txt原有内容
File file = new File(filePath);
FileWriter fw = new FileWriter(file);
fw.write("");
//获取系统时间并转换为字符串
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now_time = new Date();
String now_str = format.format(now_time);
//内容更新
StringBuffer strNew = new StringBuffer();
strNew.append("access_token=" + getToken + "\n");
strNew.append("get_time=" + now_str);
//重新写入文件
fw.write(strNew.toString());
fw.close();
return getToken;//返回重新生成的token
} catch (Exception e) {
System.out.println("获取票据异常");
;
}
//返回重新生成的token
return null;
}
获取和发送微信消息的工具类
package cn.scada.utils.weixin;
import net.sf.json.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
public class SendMsg {
/*获取token*/
public static String getSendMsgToken() {
String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=自己的企业id" +
"自己的Secret密钥" +
"";//与AgenId(若有)对应使用
String requestMethod = "GET";
String outputStr = null;
StringBuffer buffer = null;
//创建SSLContext
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
TrustManager[] tm = {new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());
//获取SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
//设置当前实例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
//往服务器端写内容
if (null != outputStr) {
OutputStream os = conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
String accesstoken = jsonObject.getString("access_token");
System.out.println("获取到的Token---------"+accesstoken);
return accesstoken;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//发送信息
public static String SendMsgtoBody(JSONObject outputStr) throws Exception {
String requestUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send";
String requestMethod = "POST";
StringBuffer buffer = null;
//创建SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager[] tm = {new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());
//获取SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
//获取txt文件里的有效token
String token=AccessTokenUtil.readText();
URL url = new URL(requestUrl + "?" +token);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
//设置当前实例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
//往服务器端写内容
if (null != outputStr) {
OutputStream os = conn.getOutputStream();
os.write(outputStr.toString().getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
JSONObject json1 = JSONObject.fromObject(buffer.toString());
System.out.println(json1);
String msg = json1 .getString("errmsg");
return msg ;
}
}
然后实现这个
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
最后测试
public class TestRun {
public static void main(String[] args) throws Exception {
JSONObject insertdata = new JSONObject();
JSONObject content = new JSONObject();
content.put("content", "测试22");
insertdata.put("touser", 人员id);//这里是接收信息的人员id(多个人用 | 隔开)
insertdata.put("msgtype", "text");
insertdata.put("agentid", AgentId);//此处一定要与上面的自建应用AgentId对应
insertdata.put("text", content);
insertdata.put("safe", 0);//0为不保密
System.out.println(insertdata);
SendMsg.SendMsgtoBody(insertdata);
//sendWechat("测试2","bailiu");
}