RestTemplate实时接收Chunked编码传输的HTTP Response

学习调用AI接口的时候,流式响应都是使用的 Transfer-Encoding: chunked,图方便想用RestTemplate,但是平时用到的都是直接返回响应对象的类型。使用bing搜索到一种方式,使用下面的代码来读取,于是掉这个坑里了,浪费了我好长时间。

java 复制代码
ResponseEntity<Resource> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, org.springframework.core.io.Resource.class);
PrintWriter writer = httpServletResponse.getWriter();
BufferedReader bufferedReader;
try {
    bufferedReader = new BufferedReader(new InputStreamReader(responseEntity.getBody().getInputStream()));
    String line;
    while ((line = bufferedReader.readLine()) != null && !(ChatGpt3dot5Request.STREAM_MESSAGE_PREFIX + "[DONE]").equals(line)) {
        String message = getMessageFromLine(line, ChatGpt3dot5Request.STREAM_MESSAGE_PREFIX);
        writer.write(message);
        writer.flush();
    }
} catch (IOException e) {
    throw new RuntimeException(e);
}

注意,上面的代码是错误的,并不会实时读取到数据,而是会等到响应全结束之后才能读取到数据。


下面的才是正解:

java 复制代码
restTemplate.execute(apiUrl, HttpMethod.POST, restTemplate.httpEntityCallback(requestEntity), new ResponseExtractor<ClientHttpResponse>() {
    @Override
    public ClientHttpResponse extractData(ClientHttpResponse response) throws IOException {
        InputStream inputStream = response.getBody();
        /*
         * 在这个地方从inputStream中读取数据,或者调用自己的方法读取inputStream来处理数据
        */
        return response;
    }
});
相关推荐
小小放舟、2 天前
PaiCLI-Demo:从零实现 ReAct Agent + Tool Call
java·后端·intellij-idea·springboot·agent·react·tool call
碎碎念_4923 天前
前后端分离项目开发规范
nginx·vue·springboot·restful
欢醉3 天前
k8s的pod容器中微服务无法创建新线程unable to create new native thread
kubernetes·springboot
她说..5 天前
Apache Commons Lang3 Pair 完整版实战详解
java·spring·java-ee·apache·springboot
文慧的科技江湖8 天前
一文读懂光伏、储能,充电工作原理,是如何实现闭环的,其中微电网(ems)是什么;这个内容,就看懂了源网荷储。十五五规划里面最核心的能源管理内容
开源·springboot·储能·光伏
AI人工智能+电脑小能手8 天前
【大白话说Java面试题 第163题】【06_Spring篇】第23题:说说SpringBoot 自动配置原理?
java·自动配置·springboot·spi·条件注解
AI人工智能+电脑小能手8 天前
【大白话说Java面试题 第164题】【06_Spring篇】第24题:如何理解 SpringBoot 的 Starter?
java·自动配置·springboot·starter·自定义组件
极光代码工作室8 天前
基于SpringBoot的订单管理系统
java·springboot·web开发·后端开发
衍生星球10 天前
SpringBoot3 + Vue3 + 微信小程序如何学习,以及学哪些技术,组件
sql·微信小程序·uni-app·vue·springboot
她说..12 天前
Java 默认值设置方式
java·开发语言·后端·springboot