用于调用 Server 酱 API,推送消息到微信。
ServerPushUtil.java
import cn.hutool.http.HttpUtil;
import java.util.HashMap;
public class ServerPushUtil {
// 你的 SendKey,替换成自己在 Server 酱获取的 SendKey
private static final String SEND_KEY = "你的_SendKey";
/**
* 发送微信消息
* @param title 消息标题
* @param content 消息内容
*/
public static void sendWxMessage(String title, String content) {
// Server 酱 API 地址
String url = "https://sctapi.ftqq.com/" + SEND_KEY + ".send";
// 请求参数
HashMap<String, Object> params = new HashMap<>();
params.put("title", title); // 消息标题
params.put("desp", content); // 消息内容
// 发送 POST 请求
String response = HttpUtil.post(url, params);
System.out.println("推送结果:" + response);
}
public static void main(String[] args) {
// 测试发送消息
sendWxMessage("告警通知", "服务器出现异常,请立即处理!");
}
}
功能说明:
SEND_KEY
:在 Server 酱官网注册后,获得的SendKey
。你需要在https://sct.ftqq.com/
获取。sendWxMessage
:发送消息到你的微信。title
是消息的标题,content
是消息的内容。HttpUtil.post
:使用Hutool
的HttpUtil
发送 HTTP POST 请求,将消息内容通过 Server 酱推送到微信。
依赖
你需要在项目中添加 Hutool 依赖,以下是 Maven 配置:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.8.10</version> <!-- 根据实际需要选择版本 -->
</dependency>
如果你使用的是 Gradle,可以添加以下依赖:
implementation 'cn.hutool:hutool-http:5.8.10'
如何使用
- 将
SEND_KEY
替换为你在 Server 酱获取的SendKey
。 - 在合适的地方调用
ServerPushUtil.sendWxMessage
方法,例如在 Java 程序中的异常捕获部分。
例如:
try {
// 你的代码
int a = 1 / 0; // 模拟异常
} catch (Exception e) {
ServerPushUtil.sendWxMessage("异常通知", "发生异常: " + e.getMessage());
}
效果
调用后,你会在 微信服务通知 中看到推送的消息。
这个工具类非常简洁,方便你在 Java 程序中随时进行微信消息推送。