You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Postman测试Spring Boot WebSocket的sendMessage与addUser接口?

测试Spring Boot WebSocket控制器方法的具体步骤

一、Postman操作步骤

1. 订阅消息主题

在已建立的ws://localhost:8080/chat WebSocket连接窗口中,点击「Subscribe」按钮,输入订阅主题/topic/public并确认。这一步是为了接收控制器通过@SendTo广播的消息。

2. 测试addUser方法

在消息输入框中构造符合ChatMessage结构的JSON数据,示例:

{
  "sender": "test_user",
  "content": "joined the chat",
  "type": "JOIN"
}

在消息发送区的「Target」输入框填写控制器映射路径/chat.addUser,点击「Send」。

此时你会在Postman的消息接收区收到返回的ChatMessage数据,服务器端已将test_user存入会话属性。

3. 测试sendMessage方法

构造聊天消息JSON,示例:

{
  "sender": "test_user",
  "content": "Hello WebSocket!",
  "type": "CHAT"
}

在「Target」输入框填写路径/chat.sendMessage,点击「Send」。

所有订阅了/topic/public的连接都会收到这条消息,你可以打开另一个Postman窗口建立相同连接并订阅主题,验证消息广播效果。

二、浏览器控制台备选方案

如果需要快速测试,也可以用浏览器控制台结合STOMP客户端操作:

  1. 打开浏览器开发者工具(F12),执行以下代码引入STOMP.js并初始化客户端:
// 引入STOMP.js
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js';
document.head.appendChild(script);

script.onload = () => {
  const client = Stomp.client('ws://localhost:8080/chat');
  // 建立连接
  client.connect({}, () => {
    // 订阅主题
    client.subscribe('/topic/public', (msg) => {
      console.log('Received:', JSON.parse(msg.body));
    });

    // 发送addUser请求
    client.send('/chat.addUser', {}, JSON.stringify({
      sender: 'browser_user',
      content: 'joined via browser',
      type: 'JOIN'
    }));

    // 发送sendMessage请求
    client.send('/chat.sendMessage', {}, JSON.stringify({
      sender: 'browser_user',
      content: 'Message from browser',
      type: 'CHAT'
    }));
  });
};

执行后,控制台会打印收到的消息反馈。


内容的提问来源于stack exchange,提问作者Maryam Zng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:50:26