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;
    }
});
相关推荐
苏生Susheng19 小时前
【软件实施】Linux企业运维常用命令手册
java·linux·运维·服务器·springboot·springcloud·软件实施
武哥聊编程1 天前
【AI实战项目】基于LangChain4j+Springboot+Vue+RAG+PGVector的AI智能客服与工单处理系统
springboot·rag·pgvector·langchain4j
小宇宙清歡渡1 天前
Java Stream 流全面实战指南(Spring Boot 3 + JDK 17)
java·springboot·stream流
小宇宙清歡渡3 天前
SpringBoot JDK17 线程池的使用
springboot·线程池·jdk17
十五喵源码网5 天前
基于springboot2+vue2的疾病防控综合系统
java·毕业设计·springboot·论文笔记
玉&心6 天前
GraalVM 21 Native Image 编译踩坑全记录:从 class 初始化冲突到成功构建
ai·springboot·graalvm·rag
十五喵源码网6 天前
基于SpringBoot2+vue2的健身房管理系统
java·毕业设计·springboot·论文笔记
記億揺晃着的那天7 天前
从 0 到 2,000+ 次提交:ERP 四年的架构演进
架构·springboot·erp
QQ_21696290967 天前
【源码编号:project93375】SpringBoot汽车维修管理信息系统:客户车辆、维修预约、工单派发、配件结算全流程实战
java·spring boot·后端·汽车·springboot·需求分析
罗超驿9 天前
SpringMVC请求参数获取与响应处理|全套注解详解
springmvc·springboot·javaweb·请求参数·后端开发