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;
    }
});
相关推荐
下次再写6 小时前
深入浅出微服务架构:从理论到Spring Boot实战
java·微服务·springboot·springcloud·架构设计·后端开发·分布式系统
牛奶咖啡139 小时前
CI/CD——在jenkins中构建流程实现springboot项目的自动化构建与部署
java·ci/cd·k8s·jenkins·springboot·springboot制作镜像·使用源码项目制作镜像
凤山老林9 小时前
慢SQL治理:索引优化实战指南——从定位到优化的完整解决方案
java·sql·springboot·慢sql治理·sql 性能优化
哆啦A梦15882 天前
01, 前端vue3框架的快速搭建以及项目工程的讲解
前端·vue3·springboot
桃花键神3 天前
【2026精品项目】基于SpringBoot3+Vue3的校园小卖铺系统(包含源码+项目文档+SQL脚本+部署教程)
数据库·sql·vue·毕业设计·springboot
洛阳泰山4 天前
Maxkb4j集成sqlbot MCP实现企业智能问数智能体
java·ai·springboot·agent·智能问数
zc.z5 天前
基于 LangChain4j 的 RAG 工作流智能体实战
langchain·大模型·springboot·rag智能体
suweijie7685 天前
Nacos配置读取异常排查与解决指南
微服务·nacos·springboot·配置中心·问题排查
程序员老邢6 天前
【产品底稿 12】工程架构最终定型:完整模块拆分、分包规范、层级依赖与开发规约全清单
微服务·架构·springboot·多模块·技术债务
abcnull6 天前
Springboot+Vue2的Web项目小白入门Demo快速学习!
java·elementui·vue·maven·springboot·web·小白