java封装一个企业微信机器人的工具类
程序员文章站
2022-07-13 08:52:47
...
package cn.tools;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
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 java.io.IOException;
public class WeChatRobot {
private final String WEBHOOK_TOKEN;
public WeChatRobot(String token) {
WEBHOOK_TOKEN = token;
}
private String send(String textMsg) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(WEBHOOK_TOKEN);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
StringEntity se = new StringEntity(textMsg, "utf-8");
httpPost.setEntity(se);
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("发送微信机器人消息成功 " + result);
return result;
} else {
System.out.println("发送微信机器人消息失败");
}
// 关闭
httpClient.close();
response.close();
return "发送微信机器人消息失败";
}
/**
* 发送图文格式的消息
*/
public String pic(String title, String description, String url, String picurl) throws IOException {
JSONObject object = new JSONObject();
JSONObject object_news = new JSONObject();
JSONObject object_articles1 = new JSONObject();
object_articles1.put("title", title);
object_articles1.put("description", description);
object_articles1.put("url", url);
object_articles1.put("picurl", picurl);
JSONArray jsonArray = new JSONArray();
jsonArray.add(object_articles1);
object_news.put("articles", jsonArray);
object.put("msgtype", "news");
object.put("news", object_news);
return send(String.valueOf(object));
}
/**
* 发送markdown格式的消息
*/
public String markdown(String string) throws IOException {
JSONObject object = new JSONObject();
JSONObject object_markdown = new JSONObject();
object_markdown.put("content", string);
object.put("msgtype", "markdown");
object.put("markdown", object_markdown);
return send(String.valueOf(object));
}
/**
* 发送text格式的消息
*/
public String text(String mag, String[] atName, String[] atMobile) throws IOException {
JSONObject object_text = new JSONObject();
JSONObject object = new JSONObject();
object_text.put("content", mag);
object_text.put("mentioned_list", atName);
object_text.put("mentioned_mobile_list", atMobile);
object.put("msgtype", "text");
object.put("text", object_text);
return send(String.valueOf(object));
}
}
上一篇: 机器学习——集成算法
下一篇: MATLAB图像预处理