微信测试公众号消息推送
1、点击https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login获取到appID和appsecret
2、新建测试模板
3、java实体类代码
package ideal4j.leisure.common.wechat.messagePush.bo;
/**
* 微信推送消息实体类
* @author yj
* @CreateDate 2018-04-04
* @param
* 模板消息需要传入的数据可在此类建立实体类
*/
public class Massages {
//微信名称openid
private String wxName;
public String getWxName() {
return wxName;
}
public void setWxName(String wxName) {
this.wxName = wxName;
}
}
4、模板实体类
package ideal4j.leisure.common.wechat.messagePush.bo;
/**
*
* @author yj
* 模板实体类
*
*/
public class TemplateData {
private String value;
private String color;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
5、token实体类
package ideal4j.leisure.common.wechat.messagePush.bo;
/**
* 凭证
* @author yj
* @date 2018-04-03
*/
public class Token {
// 接口访问凭证
private String accessToken;
// 凭证有效期,单位:秒
private int expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
6、消息模板实体类
package ideal4j.leisure.common.wechat.messagePush.bo;
import java.util.Map;
/**
*
* @author yj
* 微信模板
*
*/
public class WxTemplate {
/**
* 模板消息id
*/
private String template_id;
/**
* 用户openId
*/
private String touser;
/**
* URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)
*/
private String url;
/**
* 标题颜色
*/
private String topcolor;
/**
* 详细内容
*/
private Map<String,TemplateData> data;
public String getTemplate_id() {
return template_id;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTopcolor() {
return topcolor;
}
public void setTopcolor(String topcolor) {
this.topcolor = topcolor;
}
public Map<String, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
7、工具类
package ideal4j.leisure.common.wechat.messagePush;
//获取用户信息 的url请求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONException;
import ideal4j.leisure.common.wechat.messagePush.bo.Token;
import ideal4j.leisure.common.wechat.messagePush.MyX509TrustManager;
import net.sf.json.JSONObject;
/**
* 通用工具类
* @author yj
* @date 2018-04-03
*/
public class CommonUtil {
private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
// 凭证获取(GET)
public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* utf-8编码
*/
static class Utf8ResponseHandler implements ResponseHandler<String> {
public String handleResponse(final HttpResponse response)
throws HttpResponseException, IOException {
final StatusLine statusLine = response.getStatusLine();
final HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
return entity == null ? null : EntityUtils
.toString(entity, "UTF-8");
}
}
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @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();
System.out.println("requestUrl:"+requestUrl);
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("https请求异常:{}", e);
}
return jsonObject;
}
/**
* 获取接口访问凭证
*
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static Token getToken(String appid, String appsecret) {
Token token = null;
String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
// 发起GET请求获取凭证
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
if (null != jsonObject) {
try {
token = new Token();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (JSONException e) {
token = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return token;
}
}
8、信任管理器
package ideal4j.leisure.common.wechat.messagePush;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 信任管理器
* @author yj
* @date 2018-04-04
*/
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;
}
}
9、WechatMessagePush类
package ideal4j.leisure.common.wechat;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ideal4j.leisure.common.wechat.messagePush.CommonUtil;
import ideal4j.leisure.common.wechat.messagePush.bo.Massages;
import ideal4j.leisure.common.wechat.messagePush.bo.Token;
import ideal4j.leisure.source.util.HttpRequestUtil;
import ideal4j.leisure.source.util.JsonUtil;
import net.sf.json.JSONObject;
/**
* 微信消息推送模板1:
* 调用是传入massages.setWxName();放入openid
* @author YANGYANG
*
*/
public class WechatMessagePush {
private static final Logger logger = LoggerFactory.getLogger(WechatMessagePush.class);
/**关注者url*/
public static final String getUser_Url = "https://api.weixin.qq.com/cgi-bin/user/get";
public void wxTuisong(Massages massages){
//微信接口
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
Token token = headtoken ("wx899b1dd13f54d605","8165baccd4536836fcb08783c727b03d");//获取token
url = url.replace("ACCESS_TOKEN", token.getAccessToken());//转换为响应接口模式
List<String> list = this.getWechatAllUser(token.getAccessToken());
massages.setWxName(list.get(0));//微信名称openid
//封装数据
JSONObject json = new JSONObject();
json.put("touser",massages.getWxName());//接收者wxName //微信名称openid
json.put("template_id", "sb4hC7jeWsYLf_qwarClIZ1Id_fDXGlCCusBhKbES9w");//消息模板
json.put("url", "https://www.baidu.com/");//填写url可查看详情
JSONObject dd = new JSONObject();
JSONObject dd2 = new JSONObject();
dd2.put("value", "消息提示");//消息提示
dd2.put("color", "#173177");
dd.put("first", dd2);
JSONObject ee2 = new JSONObject();
ee2.put("value", "你从园区门口到停车场的路线导航");
ee2.put("color", "#173177");
dd.put("keyword1", ee2);
JSONObject ee3 = new JSONObject();
ee3.put("value", "不记得模板了。。。");
ee3.put("color", "#173177");
dd.put("keyword2", ee3);
json.put("data", dd);
logger.info("json.toString():"+json.toString());
JSONObject js = CommonUtil.httpsRequest(url, "POST", json.toString());
logger.info("js=="+js);
}
/**
* 请求token
* @param appId
* @param appSrecet
* @return
*/
public static Token headtoken (String appId,String appSrecet){
Token token = new Token();
token = CommonUtil.getToken(appId, appSrecet);
return token;
}
/**
* 获取所有的用户
* @param token
* @return
*/
@SuppressWarnings("unchecked")
public List<String> getWechatAllUser(String token){
logger.info("=========获取所有用户的openid====token=========="+token);
String parm2= "access_token="+ token +"&next_openid=";
String AllUser = HttpRequestUtil.sendGet(this.getUser_Url,parm2 ) ;
Map<String, Object> getUser_result = JsonUtil.jsonToMap(AllUser);
Map<String, Object> result = (Map<String, Object>) getUser_result.get("data");
List<String> userList = null;
if(!"".equals(result.get("count"))){
userList = (List<String>) result.get("openid");
}
return userList;
}
}
10、调用类
package ideal4j.leisure.platform.wechat.messagePush.action;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ideal4j.leisure.common.wechat.WechatMessagePush;
import ideal4j.leisure.common.wechat.messagePush.bo.Massages;
@Controller
@RequestMapping("/wechat/message")
public class WechatValidToken {
@RequestMapping(value="/valid", method = RequestMethod.GET)
public String wxTuisong(Massages massages){
WechatMessagePush mess = new WechatMessagePush();
mess.wxTuisong(massages);
return "wechat/parkMap/list";
}
}
10、其他类只要复值粘贴即可,需要修改WechatMessagePush类的appID,appsecret,模板id
11、这些类是框架自带的类 ,有则不需要复制,没有可以复制
package ideal4j.leisure.source.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpRequestUtil {
private static final Logger logger = LoggerFactory
.getLogger(HttpRequestUtil.class);
//连接超时时间
private static final int connectTimeout = 30000;
//读取超时时间
private static final int readTimeout = 30000;
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
// 设置 HttpURLConnection的字符编码
//conn.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
//line = new String(line.toString().getBytes("iso8859-1"), "utf-8");
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
logger.info("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// 设置 HttpURLConnection的字符编码
//conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
//line = new String(line.toString().getBytes("iso8859-1"), "utf-8");
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
logger.info("发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
* @throws Exception
*/
public static String doPost(String url, String param)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl
.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(readTimeout);
conn.setConnectTimeout(readTimeout);
if (param != null && !param.trim().equals(""))
{
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, Map<String,Object> param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// 设置 HttpURLConnection的字符编码
//conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
//line = new String(line.toString().getBytes("iso8859-1"), "utf-8");
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
logger.info("发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String do_post(String url, String param)
{
String boundary = "o---------------o";
OutputStream out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl
.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary="+boundary);
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(readTimeout);
conn.setConnectTimeout(readTimeout);
if (param != null && !param.trim().equals(""))
{
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary).append("\r\n").append("Content-Disposition: form-data; name=\"params\"")
.append("\r\n\r\n").append(param).append("\r\n").append("--").append(boundary);
// 获取URLConnection对象对应的输出流
out = new DataOutputStream(conn.getOutputStream());
// 发送请求参数
out.write(strBuf.toString().getBytes());
// flush输出流的缓冲
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}
package ideal4j.leisure.source.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.Gson;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* JSON转换工具类
*
* @author jackie
*
*/
public class JsonUtil {
/**
* 对象转换成JSON字符串
*
* @param obj 需要转换的对象
* @return 对象的string字符
*/
public static String toJson(Object obj) {
JSONObject jSONObject = JSONObject.fromObject(obj);
return jSONObject.toString();
}
/**
* JSON字符串转换成对象
*
* @param jsonString 需要转换的字符串
* @param type 需要转换的对象类型
* @return 对象
*/
@SuppressWarnings("unchecked")
public static <T> T fromJson(String jsonString, Class<T> type) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
return (T) JSONObject.toBean(jsonObject, type);
}
/**
* 将JSONArray对象转换成list集合
*
* @param jsonArr
* @return
*/
public static List<Object> jsonToList(JSONArray jsonArr) {
List<Object> list = new ArrayList<Object>();
for (Object obj : jsonArr) {
if (obj instanceof JSONArray) {
list.add(jsonToList((JSONArray) obj));
} else if (obj instanceof JSONObject) {
list.add(jsonToMap((JSONObject) obj));
} else {
list.add(obj);
}
}
return list;
}
/**
* 将json字符串转换成map对象
*
* @param json
* @return
*/
public static Map<String, Object> jsonToMap(String json) {
JSONObject obj = JSONObject.fromObject(json);
return jsonToMap(obj);
}
/**
* 将JSONObject转换成map对象
*
* @param json
* @return
*/
public static Map<String, Object> jsonToMap(JSONObject obj) {
Set<?> set = obj.keySet();
Map<String, Object> map = new HashMap<String, Object>(set.size());
for (Object key : obj.keySet()) {
Object value = obj.get(key);
if (value instanceof JSONArray) {
map.put(key.toString(), jsonToList((JSONArray) value));
} else if (value instanceof JSONObject) {
map.put(key.toString(), jsonToMap((JSONObject) value));
} else {
map.put(key.toString(), obj.get(key));
}
}
return map;
}
/**
* list转成json格式的字符串
*/
@SuppressWarnings("rawtypes")
public static String listtojson(List list) {
Gson gjson = new Gson();
String json = gjson.toJson(list);
return json;
}