HTTP非流式请求 vs HTTP流式请求
文章目录
- HTTP 非流式请求 vs 流式请求
- 一、核心区别
- 服务端代码示例(Node.js/Express)
- 非流式请求处理
- 流式请求处理
- 客户端请求示例
- 非流式请求(浏览器fetch)
- 流式请求处理(浏览器fetch)
- Python客户端示例(Requests库)
- 非流式请求
- 流式请求处理
- 关键特性对比
- 注意事项
HTTP 非流式请求 vs 流式请求
一、核心区别
-
非流式请求(传统HTTP请求):
- 客户端发送完整请求 → 服务端处理 → 返回完整响应
- 数据一次性完整传输
- 连接立即关闭
- 适用于普通API接口
-
流式请求(Streaming Request):
- 建立持久连接通道
- 服务端可持续分块发送数据
- 客户端可实时处理数据
- 适用于实时聊天、大文件传输、日志流等场景
服务端代码示例(Node.js/Express)
非流式请求处理
app.get('/api/normal', (req, res) => {
// 一次性生成完整数据
const data = Array.from({length: 5}, (_, i) => `数据块 ${i + 1}`);
res.json({
status: 'complete',
data: data
});
});
流式请求处理
app.get('/api/stream', (req, res) => {
// 设置流式响应头
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
// 模拟持续发送数据
let count = 0;
const interval = setInterval(() => {
if (count++ < 5) {
res.write(`数据块 ${count}\n`);
} else {
clearInterval(interval);
res.end(); // 结束流
}
}, 1000);
});
客户端请求示例
非流式请求(浏览器fetch)
fetch('/api/normal')
.then(response => response.json())
.then(data => {
console.log('完整数据:', data);
});
流式请求处理(浏览器fetch)
fetch('/api/stream')
.then(async response => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while(true) {
const { done, value } = await reader.read();
if(done) break;
console.log('收到数据块:', decoder.decode(value));
}
});
Python客户端示例(Requests库)
非流式请求
import requests
response = requests.get('http://localhost:3000/api/normal')
print("完整响应:", response.json())
流式请求处理
import requests
with requests.get('http://localhost:3000/api/stream', stream=True) as r:
for chunk in r.iter_content(chunk_size=None):
if chunk:
print("实时数据:", chunk.decode('utf-8'))
关键特性对比
特性 | 非流式请求 | 流式请求 |
---|---|---|
响应方式 | 一次性完整返回 | 持续分块返回 |
内存占用 | 需要完整加载数据 | 按需处理数据块 |
延迟 | 等待完整数据处理 | 首字节到达即可处理 |
适用场景 | 常规API请求 | 实时数据/大文件传输 |
连接持续时间 | 立即关闭 | 保持长连接 |
客户端处理复杂度 | 简单 | 需要特殊处理逻辑 |
注意事项
- 流式请求需要设置正确的响应头(
Transfer-Encoding: chunked
) - 客户端需要处理连接中断和重连逻辑
- 服务端要合理控制并发连接数
- 浏览器端需注意跨域问题(CORS配置)
- 流式传输更适合使用WebSocket/SSE等专业协议的场景需要考虑技术选型