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;
    }
});
相关推荐
bug攻城狮11 小时前
SaaS多租户架构实践:字段隔离方案(共享数据库+共享Schema)
mysql·架构·mybatis·springboot·1024程序员节
后端小张4 天前
【JAVA 进阶】SpringBoot集成Sa-Token权限校验框架深度解析
java·spring boot·spring·架构·sa-token·springboot·权限框架
梁辰兴4 天前
企业培训笔记:外卖平台后端--套餐管理模块--新建套餐信息
笔记·vue·mybatis·springboot·外卖管理系统
No8g攻城狮5 天前
【异常解决】使用DateUtil.isSameDay()方法判断秒级时间戳是否属于同一天踩过的坑
java·jvm·spring boot·java-ee·springboot
catoop5 天前
Sprintf Boot 之 Nacos 配置中心实践(spring.config.import=optional:nacos:)
spring·springboot
zwjapple6 天前
react+springboot的Docker部署
docker·部署·springboot·react
梁辰兴6 天前
企业培训笔记:外卖平台后端--套餐管理模块--回显套餐信息
笔记·vue·mybatis·springboot·外卖管理系统
花伤情犹在7 天前
Java Stream 高级应用:优雅地扁平化(FlatMap)递归树形结构数据
java·stream·function·flatmap
姜飞祥15 天前
springboot图片上传,且同时压缩图片
springboot
_Yoke16 天前
Java 枚举多态在系统中的实战演进:从枚举策略到自动注册
java·springboot·策略模式