118 http 协议中如何实现流式的交互数据

前言

我们经常 会碰到的 基于 http 流式交互的数据方式

一般在 现在常见的大模型中, 一般是基于 websocket 来进行流式交互

这里 来介绍一下 基于 http 的流式数据交互

基于 http 协议的流式数据交互 - 服务器

主要是基于 println 和 flush

复制代码
@RestController
@RequestMapping("/HelloWorld")
public class HelloWorldController {

    @PostMapping("/flowResponse")
    public void flowResponse(HttpServletResponse response) throws Exception {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf8");
        PrintWriter pw = response.getWriter();

        for (int i = 1; i < 10; i++) {
            pw.println(String.format("this is section %s", i));
            pw.flush();
            Thread.sleep(1000);
        }
    }

}

基于 http 协议的流式数据交互 - 客户端

发送请求这边的处理如下

复制代码
/**
 * Test26PostFlowRequest
 *
 * @author Jerry.X.He <970655147@qq.com>
 * @version 1.0
 * @date 2024-07-30 21:29
 */
public class Test26PostFlowRequest {

    // Test26PostFlowRequest
    public static void main(String[] args) {

        String url = "http://localhost:8080/HelloWorld/flowResponse";
        Map<String, String> headers = URLConnectionUtils.commonHeaders();
        String postBody = "{}";
        URLConnectionUtils.postBodyWithFlow(url, headers, postBody, "utf8", line -> {
            System.out.println(line);
        });

    }

}

postBodyWithFlow 的处理如下

发送 http 请求, 然后 一行一行的处理接收到的数据

复制代码
    /**
     * postBodyWithFlow
     *
     * @return java.lang.String
     * @author Jerry.X.He
     * @date 2024/7/30 20:26
     */
    public static HttpResponse postBodyWithFlow(String urlStr, Map<String, String> headers, String postBody,
                                            String respCharset, Consumer<String> func) {
        HttpURLConnection conn = null;
        try {
            disableSSLVerification();
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");//POST GET PUT DELETE
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.connect();
            OutputStream os = conn.getOutputStream();
            os.write(postBody.getBytes());
            os.flush();
            os.close();

            HttpResponse result = new HttpResponse();
            result.setUrl(conn.getURL());
            result.setMethod(conn.getRequestMethod());
            result.setHeaders(conn.getHeaderFields());
            result.setResponseCode(conn.getResponseCode());
            result.setResponseMessage(conn.getResponseMessage());

            StringBuilder respFromServer = new StringBuilder();
            // if success, read response from server
            if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
                if (respCharset == null) {
                    respCharset = getCharsetFromServer(result);
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), respCharset));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    func.accept(line);
                    respFromServer.append(line).append("\r\n");
                }
            }

            result.setRespCharset(respCharset);
            result.setRespFromServer(respFromServer.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

演示效果

一秒中输出一个 "this is section $id"

相关推荐
2501_9216494914 小时前
期货 Tick 级数据与基金净值历史数据 API 接口详解
开发语言·后端·python·websocket·金融·区块链
独断万古他化15 小时前
【Java 实战项目】多用户网页版聊天室:消息传输模块 —— 基于 WebSocket 实现实时通信
java·spring boot·后端·websocket·ajax·mybatis
努力的lpp19 小时前
小迪安全第10天:HTTP数据包分析与构造
网络协议·安全·http
带娃的IT创业者20 小时前
WeClaw_41_桌面端与PWA文件双向传输:WebSocket与HTTP混合协议设计
websocket·网络协议·http·文件传输·pwa
左手厨刀右手茼蒿1 天前
Flutter 组件 http_requests 适配鸿蒙 HarmonyOS 实战:极简网络请求,构建边缘端轻量级 RESTful 通讯架构
网络·flutter·http
WIN-U62 天前
新版华三H3C交换机配置NTP时钟步骤 示例(命令及WEB配置)
网络协议·tcp/ip·http
nbsaas-boot2 天前
基于 HTTP 构建 MCP Tools 的完整工程解析
网络·网络协议·http·ai
王码码20352 天前
Flutter for OpenHarmony:使用 pluto_grid 打造高性能数据网格
flutter·http·华为·架构·harmonyos
先跑起来再说2 天前
从原理到实践:彻底搞懂Cookie和Session的区别
计算机网络·http·https
兰.lan2 天前
【黑马ai测试】HTTP协议-抓包工具定位-弱网测试-缺陷介绍
网络·python·网络协议·http