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;
    }
});
相关推荐
hhzz2 天前
EasyPoi的核心映射工具:@Excel注解详解
java·服务器·excel·springboot·easypoi
温暖小土2 天前
深度解析 Spring Boot 自动配置:从原理到实践
java·springboot
温暖小土2 天前
深入理解 Spring Boot 配置加载顺序:外部化配置的艺术
java·springboot
悟空码字2 天前
无缝集成指南,SpringBoot三步接入华为云短信服务
java·springboot·编程技术·后端开发·华为云短信
ghostmen2 天前
SpringBoot + Vue 实现 Python 在线调试器 - 技术方案文档
java·python·vue·springboot
小Ti客栈2 天前
Spring Boot Profile 与外部化配置详解
spring·springboot
csdnfanguyinheng2 天前
生产级的考试系统
java·springboot·考试
岁岁种桃花儿3 天前
Spring Boot Maven插件核心配置详解:从打包到部署全流程
前端·firefox·springboot
岁岁种桃花儿3 天前
Spring Boot核心插件全解析(官方+第三方,附使用场景)
log4j·springboot·插件
super_lzb3 天前
【包教包会系列】springboot将依赖jar打到指定位置
maven·springboot·springboot打包·maven打包·项目依赖打包