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;
    }
});
相关推荐
极光代码工作室15 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
周航宇JoeZhou3 天前
JP3-2-1-MyItem项目简介
java·ai·springboot·环境搭建·项目·管理·springai
剧号3 天前
互联网大厂Java面试全解析:Java SE 11, Spring Boot及微服务实战问答
java·微服务·面试·kafka·kubernetes·springboot·分布式系统
勿忘初心12214 天前
【Windows流媒体实战2】SpringBoot2.x 整合FFmpeg 完整实操教程
ffmpeg·springboot·流媒体开发·nginx-rtmp·rtmp视频录制
X-⃢_⃢-X5 天前
四、OpenFeign远程调用
java·微服务·springboot·springcloud
凤山老林6 天前
SpringBoot实战:构建优雅的全局异常处理机制
java·springboot·异常处理
长谷深风1116 天前
Java基础知识梳理(四):异常体系、finally与统一异常处理
springboot·异常处理·java基础·项目·统一异常处理·异常·finally机制
troyzhxu8 天前
列表查询的 GraphQL —— 一行代码终结你的 if-else 地狱!
java·springboot·graphql
极光代码工作室9 天前
基于SpringBoot的在线博客系统
java·springboot·web开发·后端开发
Java爱好狂.10 天前
Java就业需要学习哪些内容?
spring·程序员·springboot·架构师·java面试·java面试题·java八股文