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;
    }
});
相关推荐
刘名喜20 小时前
第22篇-数据库迁移-Liquibase
kotlin·springboot
刘名喜21 小时前
第30篇-Spring-Security-7核心概念
后端·kotlin·springboot
刘名喜2 天前
第24篇-全局异常处理
kotlin·springboot
YDS8292 天前
大营销平台 —— 架构解析和抽奖流程串联
java·springboot·ddd
刘名喜2 天前
第21篇-N+1问题与fetch-join-EntityGraph
kotlin·springboot
刘名喜3 天前
第17篇-PostgreSQL-Docker环境搭建
kotlin·springboot
刘名喜4 天前
第09篇-协程基础-Kotlin异步编程
开发语言·kotlin·springboot
刘名喜4 天前
第12篇-Gradle-Kotlin-DSL构建指南
开发语言·kotlin·springboot
极光代码工作室7 天前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
周航宇JoeZhou9 天前
JP3-2-1-MyItem项目简介
java·ai·springboot·环境搭建·项目·管理·springai