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;
    }
});
相关推荐
大学生资源网2 小时前
基于springboot的农村综合风貌展示平台设计与实现(源码+文档)
java·数据库·spring boot·后端·毕业设计·源码·springboot
大学生资源网15 小时前
java毕业设计之“知语”花卉销售网站的设计与实现源码(源代码+文档)
java·mysql·毕业设计·源码·springboot
千寻技术帮19 小时前
10371_基于Springboot的书籍影视交流论坛
mysql·毕业设计·springboot·安装·书籍影视
Han.miracle2 天前
《Spring MVC 响应机制综合实践:页面、数据、JSON 与响应配置》
java·spring·springboot
热河暖男2 天前
使用 Flying-Saucer-Pdf + velocity 模板引擎生成 PDF(解决中文和图片问题)
java·pdf·html·springboot
阿拉斯攀登3 天前
电子签名:SpringBoot + 汉王 ESP560 的考核签名项目实施方案
springboot·canvas·电子签名·电子签·汉王
invicinble3 天前
对于认识IT系统的流量,服务器承载能力
springboot
教练、我想打篮球3 天前
120 同样的 url, header, 参数, 使用 OkHttp 能够成功获取数据, 使用 RestTemplate 报错
http·okhttp·resttemplate·accept
wasteland~3 天前
Spring AI实战:SpringBoot项目结合Spring AI开发——Tool Calling(工具调用)详解与实战
springboot·工具调用·spring ai·tool calling
hopsky3 天前
Spring Boot多模块项目中程序可运行但mvn install 时找不到类
maven·springboot