package com.cloud.module.management.message.handler.mp;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cloud.module.management.common.constant.RedisKey;
import com.cloud.module.management.common.exception.BusinessException;
import com.cloud.module.management.config.WxMpConfig;
import com.cloud.module.management.dto.WxMpDTO;
import com.cloud.module.management.utils.HttpUtil;
import com.cloud.module.management.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component("mp")
public class WxMpHandler {
@Autowired
private WxMpConfig wxMpConfig;
@Autowired
private JedisUtil jedisUtil;
/**
* 获取公众号AccessToken
*
* @return
*/
public String getPublicAccessToken() throws IOException {
return getAccessToken(wxMpConfig.getAppId(), wxMpConfig.getSecret());
}
/**
* 获取key
*
* @return
*/
private String getKey() {
return RedisKey.WX_MP + wxMpConfig.getAppId() + wxMpConfig.getSecret();
}
public String getAccessToken(String appId, String secret) throws IOException {
String redisAccessToken = jedisUtil.get(getKey());
if (!ObjectUtil.isEmpty(redisAccessToken)) {
return redisAccessToken.toString();
}
String url = wxMpConfig.getTokenUrl() + StrUtil.format("grant_type=client_credential&appid={}&secret={}", appId, secret);
String res = HttpUtil.sendGet(url);
JSONObject jsonObject = JSON.parseObject(res);
if (jsonObject.containsKey("errcode")) {
log.error("获取access_token错误码:" + jsonObject.get("errcode"));
return null;
}
String accessToken = jsonObject.getString("access_token");
Integer expiresIn = jsonObject.getInteger("expires_in");
jedisUtil.set(getKey(), accessToken, expiresIn);
return accessToken;
}
public void sendMessage(WxMpDTO param) throws IOException {
if (ObjectUtil.isEmpty(param.getTouser())) {
throw new BusinessException("接收账号不允许为空");
}
if (ObjectUtil.isEmpty(param.getTemplateId())) {
throw new BusinessException("模板id不允许为空");
}
String publicAccessToken = getPublicAccessToken();
if (StrUtil.isBlank(publicAccessToken)) {
log.error("发送公众号消息:accessToken为空");
return;
}
String url = wxMpConfig.getPushUrl() + publicAccessToken;
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("touser", param.getTouser());
paramMap.put("template_id", param.getTemplateId());
paramMap.put("data", param.getDataMap());
if (param.getNeedJump()) {
Map<String, Object> dataMiniMap = new HashMap<>();
dataMiniMap.put("appid", wxMpConfig.getAppId());
dataMiniMap.put("pagepath", param.getPagePath());
paramMap.put("miniprogram", dataMiniMap);
}
this.sendMsg(url, paramMap);
}
@Retryable(maxAttempts = 3, value = {RuntimeException.class}, backoff = @Backoff(delay = 3000))
public void sendMsg(String url, Map<String, Object> paramMap) throws IOException {
String map = JSON.toJSONString(paramMap);
String res = HttpUtil.doPostString(url, map);
JSONObject jsonObject = JSON.parseObject(res);
Integer errCode = (Integer) jsonObject.get("errcode");
if (errCode != 0) {
log.error("发送公众号消息异常:userId={}|errcode={}", jsonObject.get("errcode"));
return;
}
}
}
@PostMapping("WxMpHandler")
public void WxMpHandler() {
WxMpHandler wxMpHandler = SpringContextUtil.getBean("mp");
WxMpDTO dto=new WxMpDTO();
dto.setTouser("");
dto.setTemplateId("");
Map<String, Object> map=new HashMap<>();
MpDataEntity dataEntity=new MpDataEntity();
dataEntity.setValue(LocalDate.now().toString());
dataEntity.setColor("#173177");
MpDataEntity dataEntity1=new MpDataEntity();
dataEntity1.setValue("测试");
dataEntity1.setColor("#173177");
MpDataEntity dataEntity2=new MpDataEntity();
dataEntity2.setValue("测试");
dataEntity2.setColor("#173177");
map.put("thing4",dataEntity1);
map.put("thing3", dataEntity2);
map.put("time1", dataEntity);
dto.setDataMap(map);
try {
wxMpHandler.sendMessage(dto);
}catch (Exception e)
{
e.getMessage();
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MpDataEntity {
private String value;
private String color;
}
package com.cloud.module.management.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@Slf4j
public class HttpUtil {
/**
* POST请求
*
* @param url
* @param para
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static JSONObject doPostStr(String url, String para) throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
httpost.setEntity(new StringEntity(para, "UTF-8"));
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
jsonObject = JSONObject.parseObject(result);
} catch (Exception e) {
log.error("url:{},para:{}",url,para);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return jsonObject;
}
/**
* POST请求
*
* @param url
* @param para
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static String doPostString(String url, String para) throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
httpost.setEntity(new StringEntity(para, "UTF-8"));
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
return result;
} catch (Exception e) {
log.error("url:{},para:{}",url,para);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return null;
}
/**
* POST请求 默认是
*
* @param url
* @param para
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static JSONObject doPostJSON(String url, String para) throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
log.info("url:{},para:{}",url,para);
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
StringEntity entity = new StringEntity(para, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpost.setEntity(entity);
//请求超时 http.connection.timeout
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
//读取超时 http.socket.timeout
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
// client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info("jg:" + result);
jsonObject = JSONObject.parseObject(result);
} catch (Exception e) {
log.error("url:{},para:{}",url,para);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return jsonObject;
}
/**
* POST请求 默认是
*
* @param url
* @param para
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static JSONObject doPostJSON(String url, String para, String headerName, String headerValue, int timeout) throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
log.info("url:{},para:{}",url,para);
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
StringEntity entity = new StringEntity(para, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpost.setEntity(entity);
httpost.setHeader(headerName, headerValue);
//请求超时 http.connection.timeout
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
//读取超时 http.socket.timeout
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
// client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info("jg:" + result);
jsonObject = JSONObject.parseObject(result);
} catch (Exception e) {
log.error("url:{},para:{}",url,para);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return jsonObject;
}
public static JSONObject doGetJSON(String url) throws Exception {
return doGetJSON(url,null);
}
/**
* Get请求 默认是
*
* @param url
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static JSONObject doGetJSON(String url, Map<String, Object> paramMap) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpost = new HttpGet(url);
if (paramMap != null && !paramMap.isEmpty()) {
for (String key : paramMap.keySet()) {
if (url.indexOf('?') == -1) {
url += "?" + key + "=" + paramMap.get(key);
} else {
url += "&" + key + "=" + paramMap.get(key);
}
}
}
JSONObject jsonObject = null;
try {
HttpResponse response = client.execute(httpost);
response.setHeader("Content-Type", "application/json");
HttpEntity entity = response.getEntity(); //获取响应实体
if (null != entity) {
String result = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity); //Consume response content
// log.info(result);
jsonObject = JSONObject.parseObject(result);
}
} catch (IOException e) {
log.error("url:{}",url);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return jsonObject;
}
/**
* Get请求 默认是
*
* @param url
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static String doGetJSONZip(String url) throws Exception {
InputStream is = null;
ByteArrayOutputStream os = null;
ZipInputStream zis = null;
ByteArrayOutputStream zos = null;
HttpURLConnection con = null;
String str = null;
try {
URL urlConn = new URL(url);
con = (HttpURLConnection) urlConn.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0 Chrome/31.0.1650.63 Safari/537.36");
/*1、读取压缩文件流*/
is = con.getInputStream();
int len = -1;
byte[] b = new byte[1024]; //准备一次读入10k
os = new ByteArrayOutputStream();
while ((len = is.read(b)) > -1) {
log.info(String.valueOf(len)); //每次读取长度并不总是10k
os.write(b, 0, len);
}
// con.disconnect();
/*2、解压,可以直接从URL连接的输入流解压ZipInputStream(con.getInputStream())*/
zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray()));
ZipEntry ze = zis.getNextEntry();
zos = new ByteArrayOutputStream();
while ((len = zis.read(b)) > -1) {
zos.write(b, 0, len);
}
str = new String(zos.toByteArray(), "utf-8");
}catch (Exception e){
log.error("url:{}",url);
log.error("请求异常",e);
}finally {
if(con!=null){
con.disconnect();
}
if(is!=null)
is.close();
if(os!=null)
os.close();
if(zis!=null)
zis.close();
if(zos!=null)
zos.close();
}
return str;
}
/**
* POST请求 默认是
* @param url
* @param para
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static String doPostJSONString(String url,String para) throws Exception{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
StringEntity entity = new StringEntity(para, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpost.setEntity(entity);
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
return result;
}catch (IOException e) {
log.error("url:{},para:{}",url,para);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return null;
}
/**
* POST请求
* @param url
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static String getString(String url) throws Exception{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpost = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
log.info(result);
return result;
}catch (IOException e) {
log.error("url:{}",url);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return "";
}
/**
* POST请求
* @param url
* @return
* @throws ClientProtocolException
* @throws ParseException
* @throws IOException
*/
public static JSONObject get(String url) throws Exception{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpost = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse response;
response = client.execute(httpost);
try {
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
jsonObject = JSONObject.parseObject(result);
}catch (IOException e) {
log.error("url:{}",url);
log.error("请求异常",e);
}finally {
if(httpost!=null){
httpost.releaseConnection();
}
if(client!=null){
client.close();
}
}
return jsonObject;
}
/**
* @param url
* @param params
* @return
* @throws HttpException
* @throws IOException
*/
public static String sendPost(String url,NameValuePair[] params,String authorization) throws HttpException, IOException{
HttpClient httpClient = new HttpClient();
// 设置 HTTP 连接超时 5s
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
httpClient.getParams().setContentCharset("utf-8");
// 2.生成 GetMethod 对象并设置参数
PostMethod getMethod = new UTF8PostMethod(url);
getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
if(authorization!=null)
getMethod.setRequestHeader("Authorization", authorization);
if(params!=null)
getMethod.setRequestBody(params);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);
getMethod.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
log.error("Method failed: " + getMethod.getStatusLine());
}
BufferedReader bf = null;
InputStream inputStream = null;
try {
String str = null;
inputStream = getMethod.getResponseBodyAsStream();
Reader reader = new InputStreamReader(inputStream, "utf-8");
bf = new BufferedReader(reader);
while(null != (str = bf.readLine())){
return str;
}
} catch (IOException e) {
log.error("url:{}",url);
log.error("请求异常",e);
}finally{
if(getMethod!=null){
getMethod.releaseConnection();
}
if(inputStream!=null)
inputStream.close();
if(bf!=null)
bf.close();
}
return null;
}
public static String sendPost(String url,NameValuePair[] params) throws HttpException, IOException{
return sendPost(url,params,null);
}
public static String sendPost(String url,Map<String, Object> params) throws HttpException, IOException{
return sendPost(url,getParamsStrNameValue(params));
}
public static NameValuePair[] getParamsStrNameValue(Map<String, Object> params) {//排序
NameValuePair[] pa = new NameValuePair[params.size()];
int i=0;
for (String key : params.keySet()){
pa[i++] = new NameValuePair(key,params.get(key).toString());
}
return pa;
}
/**
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public static String sendGet(String url) throws HttpException, IOException{
HttpClient httpClient = new HttpClient();
// 设置 HTTP 连接超时 5s
log.info(url);
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
httpClient.getParams().setContentCharset("utf-8");
// 2.生成 GetMethod 对象并设置参数
GetMethod getMethod = new GetMethod(url);
getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
log.error("Method failed: " + getMethod.getStatusLine());
}
BufferedReader bf = null;
InputStream inputStream = null;
try {
String str = null;
inputStream = getMethod.getResponseBodyAsStream();
Reader reader = new InputStreamReader(inputStream, "utf-8");
bf = new BufferedReader(reader);
while(null != (str = bf.readLine())){
return str;
}
} catch (IOException e) {
log.error("url:{}",url);
log.error("请求异常",e);
}finally{
if(getMethod!=null){
getMethod.releaseConnection();
}
if(inputStream!=null)
inputStream.close();
if(bf!=null)
bf.close();
}
return null;
}
/**
* http post请求,带头信息和传文件
*
* @param urlStr http请求的地址
* @param Authorization 认证密码
* @param file 文件
* @return 响应信息
*/
public static String doPost(String urlStr, String Authorization, File file) throws Exception{
log.info("url----------------> " + urlStr);
String sResponse = "{}";
CloseableHttpClient httpClient = null;
FileInputStream fileInputStream = null;
InputStream is = null;
HttpPost httpPost = null;
try {
// 提取到文件名
String fileName = file.getName();
if (null != file) {
try {
fileInputStream = new FileInputStream(file);// 与根据File类对象的所代表的实际文件建立链接创建fileInputStream对象
} catch (FileNotFoundException e) {
log.error("url:{},para:{}",urlStr);
log.error("------文件不存在或者文件不可读或者文件是目录--------");
log.error("请求异常",e);
}
// 转换成文件流
is = fileInputStream;
}
// 创建HttpClient
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(urlStr);
//设置超时时间,这个是httpclient 4.3版本之后的设置方法
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(20000)
.setConnectTimeout(20000)
.build();
httpPost.setConfig(requestConfig);
httpPost.addHeader("Authorization", Authorization);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/* 绑定文件参数,传入文件流和 contenttype,此处也可以继续添加其他 formdata 参数 */
builder.addBinaryBody("uploadFile", is, ContentType.MULTIPART_FORM_DATA, fileName);
builder.addTextBody("userName","admin");
builder.addTextBody("type","object");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
log.info("-----------------状态码--------------");
log.info("---------------------->statusCode: "+statusCode);
HttpEntity responseEntity = response.getEntity();
//响应状态码200
if (statusCode == HttpStatus.SC_OK) {
if (null != responseEntity) {
// 将响应的内容转换成字符串
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
sResponse = JSONObject.parse(result).toString();
log.info("sResponse1:--------------->" + sResponse);
}
}
//响应状态码不是200
else {
if (null != responseEntity) {
// 将响应的内容转换成字符串
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
sResponse = JSONObject.parse(result).toString();
log.info("sResponse2:--------------->" + sResponse);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
if(httpPost!=null){
httpPost.releaseConnection();
}
if (is != null) {
is.close();
}
if (null != fileInputStream) {
fileInputStream.close();
}
if (null != httpClient) {
httpClient.close();
}
}
return sResponse;
}
}