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;
    }
});
相关推荐
程序猿_极客4 天前
【免费】分享一套优质的基于SpringBoot的扶贫助农管理系统(详解)
java·springboot·课程设计·计算机项目
苏渡苇6 天前
Spring Insight 里如何把 Span 画成瀑布时间线
后端·spring·spring cloud·springboot·监控·apm
好菇娘の当自强6 天前
【Spring Boot 2.x 与 3.x YAML 配置区别详解】
springboot
cnkeysky6 天前
SpringBoot 整合 nacos 配置中心
nacos·springboot
她说..6 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
小蒜学长7 天前
大学生健康饮食的智慧管理系统(代码+数据库+LW)
java·后端·springboot·大学生·健康饮食
Luchang-Li8 天前
CUDA stream创建和依赖,多流并行
stream·cuda·并行
小蒜学长8 天前
基于SpringBoot+Vue的游戏论坛系统的设计与实现(代码+数据库+LW)
java·后端·springboot·游戏论坛系统·社区生态
新时代农民工~8 天前
【双机高可用部署方案-前后端部署】
java·nginx·springboot
愛芳芳8 天前
Swagger2 多环境动态配置实战指南
java·后端·maven·springboot·swagger