为何返回状态码200仍无法在PostMan中连接WebSocket?
WebSocket连接报错:Unexpected server response: 200
问题描述
我尝试监听特定目标的消息,因无前端环境,用Postman测试时出现如下报错:
无法连接到 ws://localhost:8081/message 00:22:19 错误: 意外的服务器响应: 200 握手详情 请求URL: http://localhost:8081/message 请求方法: GET 状态码: 200 请求头 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: RRr0MEMeU8Shs/3Z+j9w/g== Connection: upgrade Upgrade: $http_upgrade Host: localhost:8081 Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits 响应头 Set-Cookie: JSESSIONID=533006AA29B1FA7D3C103AC027D327A5; Path=/; HttpOnly X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0 X-Frame-Options: DENY Content-Type: text/html;charset=UTF-8 Content-Length: 1406 Date: Wed, 22 Mar 2023 18:52:19 GMT
问题分析
服务器返回200状态码而非WebSocket握手要求的101,说明请求未被识别为WebSocket升级请求,核心问题出在请求头配置或服务器端WebSocket支持上。
解决步骤
1. 修正请求头的Upgrade字段
请求头里的Upgrade: $http_upgrade是错误的占位符,必须改为标准值:
Upgrade: websocket
同时确认Connection字段值为Upgrade(HTTP头大小写不敏感,但按协议规范建议首字母大写)。
2. 使用Postman的专用WebSocket请求
不要通过普通HTTP GET请求手动修改头信息,直接创建Raw WebSocket请求:
- 新建请求时切换到
WebSocket选项卡 - 输入
ws://localhost:8081/message作为连接地址 - 发起连接,Postman会自动生成符合规范的握手请求头
3. 检查服务器端WebSocket配置
若修正请求后仍报错,需确认服务器已正确配置WebSocket支持:
- 比如Spring Boot项目需添加
@ServerEndpoint注解并启用WebSocket自动配置 - 确保服务器能处理
Upgrade: websocket请求,返回包含Sec-WebSocket-Accept的101响应头
内容的提问来源于stack exchange,提问作者Ashraf
相关产品推荐
相关产品推荐

