JAVA调用接口推送微信订阅消息以及获取access_token
程序员文章站
2024-01-08 14:01:40
...
package com.fd.hunxiu.lctest;
import com.alibaba.fastjson.JSONObject;
import com.fd.hunxiu.TestBase;
import com.fd.hunxiu.config.mq.RabbitConstant;
import com.fd.hunxiu.dto.TemplateDataVo;
import com.fd.hunxiu.service.WedgGiftService;
import com.fd.hunxiu.service.WedgService;
import com.fd.hunxiu.utils.GetTokenUtil;
import com.fd.hunxiu.utils.httpClient.HttpUtils;
import org.junit.Test;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.util.TreeMap;
/**
* @Description
* @Author lc
* @Date 2020/3/20 16:35
*/
public class LiucongTest extends TestBase {
public static final Logger logger = LoggerFactory.getLogger(LiucongTest.class);
@Autowired
private WedgService wedgService;
@Autowired
RedissonClient redissonClient;
@Autowired
WedgGiftService wedgGiftService;
@Autowired
RabbitConstant rabbitConstant;
@Value("${acct.ccusAcct}")
private String ccusAcct;
@Value("${fd.message.signName}")
private String signName;
@Value("${fd.dxl.templateCode}")
private String TEMPLATE_CODE;
@Value("${wx.hunxiu-c.appid}")
private String appid;
@Value("${wx.hunxiu-c.secret}")
private String secret;
@Value("${fd.access-token-redis-key}")
private String accessTokenRedisKey;
@Test
public void liucongTest() {
TreeMap<String, TreeMap<String, String>> treeMap = new TreeMap<>();
treeMap.put("thing1", TemplateDataVo.item("上海小程序开发者聚会"));
treeMap.put("data2", TemplateDataVo.item("2020-03-31"));
treeMap.put("thing3", TemplateDataVo.item("队伍约动消息通知"));
logger.info("<=================***********************=================>");
logger.info("<=================" + JSONObject.toJSON(treeMap) + "=================>");
logger.info("<=================***********************=================>");
String token = new GetTokenUtil().getToken(redissonClient, appid, secret, accessTokenRedisKey);//获取token
logger.info("<=================***********************=================>");
logger.info("<=================" + token + "=================>");
logger.info("<=================***********************=================>");
String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
TemplateDataVo templateDataVo = new TemplateDataVo();
templateDataVo.setTouser("oCS9e5YRZhX_wjD_DsXbpf6pZLy4");
templateDataVo.setTemplate_id("BIeXyORf8MeKOH4f5TEB-ItPIdTjZygM-WNS6AVg2ts");
templateDataVo.setData(treeMap);
templateDataVo.setMiniprogram_state("trial");
templateDataVo.setPage("pages/progressive/index?wedgCode=325430599128&wedgToken=d1415f16c0cc49d98fa416f25c583d33");
TreeMap<String, String> treeMap1 = new TreeMap<>();
treeMap1.put("access_token", token);
String sendData = JSONObject.toJSONString(JSONObject.toJSON(templateDataVo));
String result = HttpUtils.doPost(url, treeMap1, sendData);
System.out.println(result);
}
}
package com.fd.hunxiu.dto;
import lombok.Data;
import java.util.TreeMap;
@Data
public class TemplateDataVo {
private String touser;
private String template_id;
private String url;
private String miniprogram_state;
private String page;
private TreeMap<String, TreeMap<String, String>> data; //data数据
public static TreeMap<String, String> item(String data) {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("DATA", data);
return params;
}
public TreeMap<String, TreeMap<String, String>> getData() {
return data;
}
public void setData(TreeMap<String, TreeMap<String, String>> data) {
this.data = data;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getTemplate_id() {
return template_id;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMiniprogram_state() {
return miniprogram_state;
}
public void setMiniprogram_state(String miniprogram_state) {
this.miniprogram_state = miniprogram_state;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
@Override
public String toString() {
return "TemplateDataVo{" +
"touser='" + touser + '\'' +
", template_id='" + template_id + '\'' +
", url='" + url + '\'' +
", miniprogram_state='" + miniprogram_state + '\'' +
", page='" + page + '\'' +
", data=" + data +
'}';
}
}
package com.fd.hunxiu.utils.httpClient;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
protected static final String POST_METHOD = "POST";
private static final String GET_METHOD = "GET";
/**
* 默认的http请求执行方法
*
* @param url url 路径
* @param method 请求的方法 POST/GET
* @param map 请求参数集合
* @param data 输入的数据 允许为空
* @return result
*/
private static String HttpDefaultExecute(String url, String method, Map<String, String> map, String data) {
String result = "";
try {
url = setParmas(url, map, null);
result = defaultConnection(url, method, data);
} catch (Exception e) {
logger.error("出错参数 {}", map);
}
return result;
}
public static String httpGet(String url, Map<String, String> map) {
return HttpDefaultExecute(url, GET_METHOD, map, null);
}
public static String httpPost(String url, Map<String, String> map, String data) {
return HttpDefaultExecute(url, POST_METHOD, map, data);
}
/**
* 默认的https执行方法,返回
*
* @param url url 路径
* @param method 请求的方法 POST/GET
* @param map 请求参数集合
* @param data 输入的数据 允许为空
* @return result
*/
private static String HttpsDefaultExecute(String url, String method, Map<String, String> map, String data) {
try {
url = setParmas(url, map, null);
logger.info(data);
return defaultConnection(url, method, data);
} catch (Exception e) {
logger.error("出错参数 {}", map);
}
return "";
}
public static String doGet(String url, Map<String, String> map) {
return HttpsDefaultExecute(url, GET_METHOD, map, null);
}
public static String doPost(String url, Map<String, String> map, String data) {
return HttpsDefaultExecute(url, POST_METHOD, map, data);
}
/**
* @param path 请求路径
* @param method 方法
* @param data 输入的数据 允许为空
* @return
* @throws Exception
*/
private static String defaultConnection(String path, String method, String data) throws Exception {
if (StringUtils.isBlank(path)) {
throw new IOException("url can not be null");
}
String result = null;
URL url = new URL(path);
HttpURLConnection conn = getConnection(url, method);
if (StringUtils.isNotEmpty(data)) {
OutputStream output = conn.getOutputStream();
output.write(data.getBytes(StandardCharsets.UTF_8));
output.flush();
output.close();
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
result = IOUtils.toString(input);
input.close();
conn.disconnect();
}
return result;
}
/**
* 根据url的协议选择对应的请求方式
*
* @param url 请求路径
* @param method 方法
* @return conn
* @throws IOException 异常
*/
//待改进
protected static HttpURLConnection getConnection(URL url, String method) throws IOException {
HttpURLConnection conn;
if (StringUtils.equals("https", url.getProtocol())) {
conn = (HttpsURLConnection) url.openConnection();
} else {
conn = (HttpURLConnection) url.openConnection();
}
if (conn == null) {
throw new IOException("connection can not be null");
}
conn.setRequestProperty("Pragma", "no-cache");// 设置不适用缓存
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Connection", "Close");// 不支持Keep-Alive
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod(method);
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
return conn;
}
/**
* 根据url
*
* @param url 请求路径
* @return isFile
* @throws IOException 异常
*/
//待改进
protected static HttpURLConnection getConnection(URL url, boolean isFile) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn == null) {
throw new IOException("connection can not be null");
}
//设置从httpUrlConnection读入
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
//如果是上传文件,则设为POST
if (isFile) {
conn.setRequestMethod(POST_METHOD); //GET和 POST都可以 文件略大改成POST
}
// 设置请求头信息
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", String.valueOf(StandardCharsets.UTF_8));
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
return conn;
}
/**
* 拼接参数
*
* @param url 需要拼接参数的url
* @param map 参数
* @param charset 编码格式
* @return 拼接完成后的url
*/
public static String setParmas(String url, Map<String, String> map, String charset) throws Exception {
String result = StringUtils.EMPTY;
boolean hasParams = false;
if (StringUtils.isNotEmpty(url) && MapUtils.isNotEmpty(map)) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey().trim();
String value = entry.getValue().trim();
if (hasParams) {
builder.append("&");
} else {
hasParams = true;
}
if (StringUtils.isNotEmpty(charset)) {
builder.append(key).append("=").append(URLEncoder.encode(value, charset));
} else {
builder.append(key).append("=").append(value);
}
}
result = builder.toString();
}
URL u = new URL(url);
if (StringUtils.isEmpty(u.getQuery())) {
if (url.endsWith("?")) {
url += result;
} else {
url = url + "?" + result;
}
} else {
if (url.endsWith("&")) {
url += result;
} else {
url = url + "&" + result;
}
}
logger.debug("request url is {}", url);
return url;
}
}
package com.fd.hunxiu.utils;
import com.fd.hunxiu.utils.common.KeyConstant;
import com.fd.hunxiu.utils.httpClient.UrlUtil;
import com.fd.hunxiu.utils.redis.RedisUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 获取Token
*/
@Component
public class GetTokenUtil {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* @param redissonClient
* @param appid
* @param secret
* @return java.lang.String
* @Description 从redis获取access_token
* @Author lc
* @Date 2020/3/26 13:47
**/
public String getToken(RedissonClient redissonClient, String appid, String secret, String accessTokenRedisKey) {
String redisKey = KeyConstant.REDIS_ACCESS_TOKEN + accessTokenRedisKey;
System.out.println("accessTokenKey:====================:" + redisKey);
RBucket<Object> bucket = RedisUtil.buildNamespace(redissonClient, redisKey);
String accessToken = RedisUtil.getValueByKey(bucket, accessTokenRedisKey);
System.out.println("accessToken:====================:" + accessToken);
if (StringUtils.isNotBlank(accessToken)) {
return accessToken;
} else {
Map<String, Object> paramMap = new HashMap<>();
String token = callToken(appid, secret);//获取token
paramMap.put(accessTokenRedisKey, token);
bucket.set(paramMap);
bucket.set(paramMap, 7000, TimeUnit.SECONDS);
return token;
}
}
/**
* @param appid
* @param secret
* @return java.lang.String
* @Description 获取access_token
* @Author lc
* @Date 2020/3/26 13:48
**/
public String callToken(String appid, String secret) {
String url = "https://api.weixin.qq.com/cgi-bin/token";
Map<String, Object> map = new HashMap<>();
map.put("grant_type", "client_credential");
map.put("appid", appid);
map.put("secret", secret);
String result = UrlUtil.sendPost(url, map);
JSONObject json = JSONObject.fromObject(result);
String token = json.getString("access_token");
return token;
}
public static void main(String[] args) {
try {
System.out.println(new GetTokenUtil().callToken("******************", "******************"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取当前时间
*
* @return
*/
private String getDate() {
Date date = new Date();
String nowDate = sdf.format(date);
return nowDate;
}
}
package com.fd.hunxiu.utils.redis;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import java.util.Map;
/**
* @Description redis命名空间创建
* @Author lc
* @Date 2020/3/26 14:20
*/
public class RedisUtil {
/**
* redis命名空间构建
*
* @param redissonClient
* @param keyName key
* @return
*/
public static RBucket<Object> buildNamespace(RedissonClient redissonClient, String keyName) {
RBucket<Object> bucket = redissonClient.getBucket(keyName);
return bucket;
}
/**
* 根据key获取value
*
* @param bucket
* @param key
* @return
*/
public static String getValueByKey(RBucket<Object> bucket, String key) {
Map<String, Object> map = (Map<String, Object>) bucket.get();
String value = "";
try {
if (null != map) {
String str = (String) map.get(key);
if (StringUtils.isNotBlank(str)) {
value = str;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
package com.fd.hunxiu.utils.httpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
public class UrlUtil {
/**
* @param url 发送请求的 URL
* @param paramMap 请求参数
* @return java.lang.String 所代表远程资源的响应结果
* @Description 向指定 URL 发送POST方法的请求
* @Author lc
* @Date 2019-10-29 上午 9:26
**/
public static String sendPost(String url, Map<String, ?> paramMap) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
String param = "";
Iterator<String> it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
param += key + "=" + paramMap.get(key) + "&";
}
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
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);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
package com.fd.hunxiu;
import com.fd.businessengine.common.util.SpringBootUtil;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HunXiuClientApplication.class)
@ActiveProfiles("dev")
public abstract class TestBase {
public TestBase() {
SpringBootUtil.initProperty();
}
@Autowired
Tracer tracer;
@Before
public void before() {
tracer.createSpan("test");
}
/**
* 在所有测试运行完毕后关闭控制台输出,因为Spring Netflix内部Bug会在测试运行完毕后结束进程时产生与测试无关的异常
*/
@AfterClass
public static void ignoreConsolePrint() {
OutputStream ignoreOutputStream = new OutputStream() {
@Override
public void write(int b) throws IOException {
//ignore
}
};
System.setOut(new PrintStream(ignoreOutputStream));
System.setErr(new PrintStream(ignoreOutputStream));
}
public static void main(String[] args) {
int a = 1;
for (int i = 0; i < a; i++) {
System.out.println(i);
}
}
}
上一篇: 复选框操作