Java案例如何实现飞书通知?

wen python案例 2

本文目录导读:

Java案例如何实现飞书通知?

  1. 方案一:Webhook机器人(最简单)
  2. 方案二:自定义应用(功能更强大)
  3. 方案三:Spring Boot集成(推荐)
  4. 方案四:使用OKHttp(高效)
  5. 消息类型说明
  6. 最佳实践建议

我来详细介绍Java实现飞书通知的几种方式,包括Webhook机器人和自定义应用两种方案。

Webhook机器人(最简单)

创建飞书机器人

在飞书群聊中添加群机器人,获取Webhook地址。

Java实现代码

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.json.JSONObject;
public class FeishuWebhookNotifier {
    private static final String WEBHOOK_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/your-webhook-url";
    /**
     * 发送文本消息
     */
    public static void sendTextMessage(String content) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(WEBHOOK_URL);
            // 构建消息体
            JSONObject message = new JSONObject();
            message.put("msg_type", "text");
            JSONObject contentJson = new JSONObject();
            contentJson.put("text", content);
            message.put("content", contentJson);
            // 设置请求实体
            StringEntity entity = new StringEntity(message.toString(), "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            // 发送请求
            httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 发送富文本消息
     */
    public static void sendRichTextMessage(String title, String content) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(WEBHOOK_URL);
            JSONObject message = new JSONObject();
            message.put("msg_type", "post");
            JSONObject contentJson = new JSONObject();
            contentJson.put("zh_cn", new JSONObject()
                .put("title", title)
                .put("content", new Object[][]{
                    {new JSONObject().put("tag", "text").put("text", content)}
                })
            );
            message.put("content", contentJson);
            StringEntity entity = new StringEntity(message.toString(), "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 发送Markdown消息
     */
    public static void sendMarkdownMessage(String content) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(WEBHOOK_URL);
            JSONObject message = new JSONObject();
            message.put("msg_type", "interactive");
            JSONObject card = new JSONObject();
            JSONObject header = new JSONObject()
                .put("title", new JSONObject()
                    .put("tag", "plain_text")
                    .put("content", "通知消息"));
            card.put("header", header);
            JSONObject element = new JSONObject()
                .put("tag", "markdown")
                .put("content", content);
            card.put("elements", new Object[]{element});
            message.put("card", card);
            StringEntity entity = new StringEntity(message.toString(), "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// 使用示例
public class Main {
    public static void main(String[] args) {
        // 发送文本消息
        FeishuWebhookNotifier.sendTextMessage("Hello, 飞书! \n这是测试消息");
        // 发送Markdown消息
        String markdownContent = "## 系统告警\n" +
                                 "**服务器**: 127.0.0.1\n" +
                                 "**CPU使用率**: 95%\n" +
                                 "**时间**: 2024-01-01 12:00:00";
        FeishuWebhookNotifier.sendMarkdownMessage(markdownContent);
    }
}

自定义应用(功能更强大)

创建飞书应用

  1. 前往 飞书开放平台
  2. 创建应用,获取 App ID 和 App Secret

Maven依赖

<dependency>
    <groupId>com.larksuite.oapi</groupId>
    <artifactId>oapi-sdk</artifactId>
    <version>2.0.4</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.25</version>
</dependency>

完整实现代码

import com.alibaba.fastjson.JSONObject;
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 java.io.BufferedReader;
import java.io.InputStreamReader;
public class FeishuAppNotifier {
    private static final String APP_ID = "your-app-id";
    private static final String APP_SECRET = "your-app-secret";
    private static final String TENANT_ACCESS_TOKEN_URL = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
    /**
     * 获取 tenant_access_token
     */
    private static String getTenantAccessToken() throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(TENANT_ACCESS_TOKEN_URL);
            JSONObject requestBody = new JSONObject();
            requestBody.put("app_id", APP_ID);
            requestBody.put("app_secret", APP_SECRET);
            StringEntity entity = new StringEntity(requestBody.toString(), "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            StringBuilder response = new StringBuilder();
            httpClient.execute(httpPost, httpResponse -> {
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return null;
            });
            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
            return jsonResponse.getString("tenant_access_token");
        }
    }
    /**
     * 发送消息给用户
     */
    public static void sendMessageToUser(String userId, String content) throws Exception {
        String token = getTenantAccessToken();
        String url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Authorization", "Bearer " + token);
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
            JSONObject message = new JSONObject();
            message.put("receive_id", userId);
            message.put("msg_type", "text");
            message.put("content", new JSONObject().fluentPut("text", content).toString());
            StringEntity entity = new StringEntity(message.toString(), "UTF-8");
            httpPost.setEntity(entity);
            httpClient.execute(httpPost);
        }
    }
    /**
     * 发送消息到群聊
     */
    public static void sendMessageToGroup(String chatId, String content) throws Exception {
        String token = getTenantAccessToken();
        String url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Authorization", "Bearer " + token);
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
            JSONObject message = new JSONObject();
            message.put("receive_id", chatId);
            message.put("msg_type", "interactive");
            // 构建消息卡片
            JSONObject card = new JSONObject();
            JSONObject header = new JSONObject()
                .fluentPut("title", new JSONObject()
                    .fluentPut("tag", "plain_text")
                    .fluentPut("content", "系统通知"));
            card.put("header", header);
            JSONObject element = new JSONObject()
                .fluentPut("tag", "markdown")
                .fluentPut("content", content);
            card.put("elements", new Object[]{element});
            message.put("content", card.toString());
            StringEntity entity = new StringEntity(message.toString(), "UTF-8");
            httpPost.setEntity(entity);
            httpClient.execute(httpPost);
        }
    }
}

Spring Boot集成(推荐)

创建配置类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "feishu")
public class FeishuConfig {
    private String webhookUrl;
    private String appId;
    private String appSecret;
    // getters and setters
}

application.yml配置

feishu:
  webhook-url: https://open.feishu.cn/open-apis/bot/v2/hook/your-webhook-url
  app-id: your-app-id
  app-secret: your-app-secret

创建Service类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class FeishuNotificationService {
    private static final Logger log = LoggerFactory.getLogger(FeishuNotificationService.class);
    @Autowired
    private FeishuConfig feishuConfig;
    @Autowired
    private RestTemplate restTemplate;
    public void sendNotification(String message, String messageType) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            JSONObject requestBody = new JSONObject();
            requestBody.put("msg_type", messageType);
            JSONObject content = new JSONObject();
            content.put("text", message);
            requestBody.put("content", content);
            HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers);
            ResponseEntity<String> response = restTemplate.postForEntity(
                feishuConfig.getWebhookUrl(), 
                request, 
                String.class
            );
            if (response.getStatusCode() == HttpStatus.OK) {
                log.info("飞书通知发送成功");
            }
        } catch (Exception e) {
            log.error("飞书通知发送失败", e);
        }
    }
}

使用示例

@RestController
@RequestMapping("/api/notification")
public class NotificationController {
    @Autowired
    private FeishuNotificationService feishuService;
    @PostMapping("/send")
    public String send(@RequestBody NotificationRequest request) {
        // 简单文本消息
        feishuService.sendNotification("服务器告警:CPU使用率超过90%", "text");
        // Markdown格式
        String markdown = "**服务器状态**\n" +
                          "- IP: 192.168.1.1\n" +
                          "- CPU: 95%\n" +
                          "- 内存: 80%";
        feishuService.sendNotification(markdown, "interactive");
        return "success";
    }
}

使用OKHttp(高效)

import okhttp3.*;
public class FeishuOkHttpNotifier {
    private static final OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    public static void sendMessage(String webhookUrl, String content) {
        try {
            JSONObject json = new JSONObject();
            json.put("msg_type", "text");
            json.put("content", new JSONObject().fluentPut("text", content));
            RequestBody body = RequestBody.create(json.toString(), JSON);
            Request request = new Request.Builder()
                .url(webhookUrl)
                .post(body)
                .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.err.println("发送失败: " + e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    System.out.println("发送成功: " + response.body().string());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

消息类型说明

消息类型 说明 适用场景
text 纯文本消息 简单通知
post 富文本消息 结构化信息
interactive 消息卡片 复杂交互通知
image 图片消息 图表展示
share_chat 分享群聊 群聊推荐

最佳实践建议

  1. 异步发送:使用线程池或MQ异步发送通知
  2. 错误重试:实现重试机制
  3. 限流控制:飞书API有频率限制
  4. 消息模板:预定义消息模板
  5. 日志记录:记录发送状态

选择合适的方案,根据你的具体需求实现飞书通知功能。

抱歉,评论功能暂时关闭!