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;
    }
});
相关推荐
fouryears_2341713 小时前
@PathVariable与@RequestParam的区别
java·spring·mvc·springboot
飞翔的佩奇2 天前
OpenTelemetry学习笔记(十二):在APM系统中,属性的命名空间处理遵循规则
笔记·学习·springboot·sdk·apm·opentelemetry
rhyme3 天前
源码浅析:SpringBoot main方法结束为什么程序不停止
springboot·markdown·java多线程·源码解析·mermaid
fouryears_234173 天前
Spring MVC 统一响应格式:ResponseBodyAdvice 从浅入深
java·spring·mvc·springboot
666HZ6664 天前
若依框架角色菜单权限
java·spring·springboot
鼠鼠我捏,要死了捏5 天前
Spring Boot中REST与gRPC并存架构设计与性能优化实践指南
springboot·restful·grpc
fanTuanye7 天前
前端环境搭建---基于SpringBoot+MySQL+Vue+ElementUI+Mybatis前后端分离面向小白管理系统搭建
vue.js·elementui·npm·springboot·前端开发环境搭建
飞鸟_Asuka8 天前
SpringBoot集成测试笔记:缩小测试范围、提高测试效率
java·单元测试·集成测试·springboot
nextera-void8 天前
SpringBoot 3.0 挥别 spring.factories,拥抱云原生新纪元
java·开发语言·springboot
TinpeaV8 天前
Springboot3整合Elasticsearch8(elasticsearch-java)
java·大数据·elasticsearch·搜索引擎·springboot