Java接入微信告警實現程式碼(Cat點評)
阿新 • • 發佈:2018-12-17
企業微信下載
依賴新增
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId> httpclient</artifactId>
<version>4.5.5</version>
</dependency>
程式碼實現
- 所需實體類
package com.platform.monitor.vo;
/**
* @ClassName: IacsUrlDataVo
* @Author: shenlele
* @Date: 2018/10/11 11:01
* @Description:
*/
public class IacsUrlDataVo {
String corpid;
String corpsecret;
String Get_Token_Url;
String SendMessage_Url;
public String getCorpid() {
return corpid;
}
public void setCorpid(String corpid) {
this.corpid = corpid;
}
public String getCorpsecret() {
return corpsecret;
}
public void setCorpsecret(String corpsecret) {
this.corpsecret = corpsecret;
}
public void setGet_Token_Url(String corpid,String corpsecret) {
this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
}
public String getGet_Token_Url() {
return Get_Token_Url;
}
public String getSendMessage_Url(){
SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
return SendMessage_Url;
}
}
package com.platform.monitor.vo;
/**
* @ClassName: IacsWeChatDataVo
* @Author: shenlele
* @Date: 2018/10/11 11:02
* @Description:
*/
public class IacsWeChatDataVo {
String touser;
String msgtype;
int agentid;
Object text;//實際接收Map型別資料
public Object getText() {
return text;
}
public void setText(Object text) {
this.text = text;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public int getAgentid() {
return agentid;
}
public void setAgentid(int agentid) {
this.agentid = agentid;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
}
- 資訊處理類
package com.platform.monitor.common.util;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.platform.monitor.vo.IacsUrlDataVo;
import com.platform.monitor.vo.IacsWeChatDataVo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName: SendMsgUtils
* @Author: shenlele
* @Date: 2018/10/11 14:08
* @Description:
*/
public class SendWeChatUtils {
RestTemplate restTemplate = new RestTemplate();
private CloseableHttpClient httpClient;
private HttpPost httpPost;//用於提交登陸資料
private HttpGet httpGet;//用於獲得登入後的頁面
public static final String CONTENT_TYPE = "Content-Type";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Gson gson = new Gson();
/**
* 微信授權請求,GET型別,獲取授權響應,用於其他方法擷取token
*
* @param Get_Token_Url
* @return String 授權響應內容
* @throws IOException
*/
public String toAuth(String Get_Token_Url) throws IOException {
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(Get_Token_Url);
CloseableHttpResponse response = httpClient.execute(httpGet);
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
} finally {
response.close();
}
LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
return resp;
}
/**
* 獲取toAuth(String Get_Token_Url)返回結果中鍵值對中access_token鍵的值
*
* @param corpid 應用組織編號 corpsecret 應用祕鑰
*/
public String getToken(String corpid, String corpsecret) throws IOException {
SendWeChatUtils sw = new SendWeChatUtils();
IacsUrlDataVo uData = new IacsUrlDataVo();
uData.setGet_Token_Url(corpid, corpsecret);
String resp = sw.toAuth(uData.getGet_Token_Url());
Map<String, Object> map = gson.fromJson(resp,
new TypeToken<Map<String, Object>>() {
}.getType());
return map.get("access_token").toString();
}
/**
* @param touser 傳送訊息接收者 ,msgtype訊息型別(文字/圖片等),
* @param application_id 應用編號。
* @return String
* @Title:建立微信傳送請求post資料
*/
public String createpostdata(String touser, String msgtype,
int application_id, String contentKey, String contentValue) {
IacsWeChatDataVo wcd = new IacsWeChatDataVo();
wcd.setTouser(touser);
wcd.setAgentid(application_id);
wcd.setMsgtype(msgtype);
Map<Object, Object> content = new HashMap<Object, Object>();
content.put(contentKey, contentValue + "\n--------\n" + df.format(new Date()));
wcd.setText(content);
return gson.toJson(wcd);
}
/**
* @param charset 訊息編碼 ,contentType 訊息體內容型別,
* @param url 微信訊息傳送請求地址,data為post資料,token鑑權token
* @return String
* @Title 建立微信傳送請求post實體
*/
public String post(String charset, String contentType, String url,
String data, String token) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url + token);
httpPost.setHeader(CONTENT_TYPE, contentType);
httpPost.setEntity(new StringEntity(data, charset));
CloseableHttpResponse response = httpclient.execute(httpPost);
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, charset);
EntityUtils.consume(entity);
} finally {
response.close();
}
LoggerFactory.getLogger(getClass()).info(
"call [{}], param:{}, resp:{}", url, data, resp);
return resp;
}
/**
* 處理微信接收人資訊
*
* @return java.lang.String
* @Author shenlele
* @Date 2018/10/12 10:54
* @Param [receiver]
**/
public String toUser(String[] receiver) {
String[] arr = this.toString(receiver).split(",");
StringBuffer sb = new StringBuffer();
//將不含有@符號的郵箱地址取出
for (String str : arr) {
if (str.indexOf("@") == -1) {
sb.append(str + "|");
}
}
return sb.toString().substring(0, sb.length() - 1);
}
/**
* 陣列轉字串
*
* @return java.lang.String
* @Author shenlele
* @Date 2018/10/12 11:27
* @Param [array]
**/
public String toString(String[] array) {
StringBuffer sb = new StringBuffer();
for (String str : array) {
sb.append(str + ",");
}
return sb.toString().substring(0, sb.length() - 1);
}
}
- 常量類
package com.platform.monitor.common;
public class Constants {
//微信企業ID
public static final String CORPID = "wwf727081s21717263";
//微信企業密匙
public static final String CORPSECRET = "MmiCj4JMt9jJIdxcPSDZjppPkHz6KSCSC3ko-fmKBU";
//微信應用ID
public static final int APPLICATION_ID = 1000002;
//字元編碼集
public static final String CHARSET = "utf-8";
}
- 介面controller類
package com.platform.monitor.controller;
import com.platform.monitor.common.Constants;
import com.platform.monitor.common.util.SendMsgUtils;
import com.platform.monitor.common.util.SendWeChatUtils;
import com.platform.monitor.vo.IacsUrlDataVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
/**
* @ClassName: IacsWeChatController
* @Author: shenlele
* @Date: 2018/10/11 14:19
* @Description:
*/
@RestController
public class WeChatController {
/**
* 傳送微信方法
*
* @return void
* @Author shenlele
* @Date 2018/10/11 14:19
* @Param [request]
**/
@PostMapping({"/sendWeChat"})
public void send(HttpServletRequest request) {
Map<String, String[]> map = request.getParameterMap();
SendWeChatUtils msgUtils = new SendWeChatUtils();
try {
String token = msgUtils.getToken(Constants.CORPID, Constants.CORPSECRET);
String postdata = msgUtils.createpostdata(msgUtils.toUser(map.get("email")), "text", Constants.APPLICATION_ID, "content", msgUtils.toString(map.get("content")));
String resp = msgUtils.post(Constants.CHARSET, SendMsgUtils.CONTENT_TYPE, (new IacsUrlDataVo()).getSendMessage_Url(), postdata, token);
System.out.println("獲取到的token======>" + token);
System.out.println("請求資料======>" + postdata);
System.out.println("傳送微信的響應資料======>" + resp);
} catch (IOException e) {
e.printStackTrace();
}
}
}