您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用REST模板Java Spring MVC从服务器下载大文件

使用REST模板Java Spring MVC从服务器下载大文件

这是我的方法。基于springJira问题的提示

RestTemplate restTemplate // = ...;

// Optional Accept header
RequestCallback requestCallback = request -> request.getHeaders()
        .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

// Streams the response instead of loading it all in memory
ResponseExtractor<Void> responseExtractor = response -> {
    // Here I write the response to a file but do what you like
    Path path = Paths.get("some/path");
    Files.copy(response.getBody(), path);
    return null;
};
restTemplate.execute(URI.create("www.something.com"), HttpMethod.GET, requestCallback, responseExtractor);

从前面提到的吉拉问题:

请注意,你不能简单地从提取器返回InputStream,因为到execute方法返回时,基础连接和流已经关闭

Update for Spring 5

Spring 5引入了WebClient允许异步(例如,非阻塞)http请求的类。从文档:

与RestTemplate相比,WebClient是:

java 2022/1/1 18:18:59 有404人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶