Java 工具类调用Server 酱推送消息

用于调用 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:使用 HutoolHttpUtil 发送 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'

如何使用

  1. SEND_KEY 替换为你在 Server 酱获取的 SendKey
  2. 在合适的地方调用 ServerPushUtil.sendWxMessage 方法,例如在 Java 程序中的异常捕获部分。

例如:

try {
    // 你的代码
    int a = 1 / 0;  // 模拟异常
} catch (Exception e) {
    ServerPushUtil.sendWxMessage("异常通知", "发生异常: " + e.getMessage());
}

效果

调用后,你会在 微信服务通知 中看到推送的消息。

这个工具类非常简洁,方便你在 Java 程序中随时进行微信消息推送。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值