使用RestTemplate获取InputStream [英] Getting InputStream with RestTemplate

查看:2117
本文介绍了使用RestTemplate获取InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用URL类从中读取InputStream。我有什么方法可以使用RestTemplate吗?

I am using URL class to read an InputStream from it. Is there any way I can use RestTemplate for this?

InputStream input = new URL(url).openStream();
JsonReader reader = new JsonReader(new InputStreamReader(input, StandardCharsets.UTF_8.displayName())); 

如何使用<$获取 InputStream c $ c> RestTemplate 而不是使用 URL

How can I get InputStream with RestTemplate instead of using URL?

推荐答案

你不应该。 RestTemplate 用于封装处理响应(和请求)内容。

You shouldn't. RestTemplate is meant to encapsulate processing the response (and request) content.

相反,您可以注册相应的 HttpMessageConverter 对象。那些人可以通过 InputStream /springframework/http/HttpInputMessage.html\"rel =nofollow noreferrer> HttpInputMessage object。

Instead, you can register appropriate HttpMessageConverter objects. Those will have access to the response's InputStream, through an HttpInputMessage object.

正如Abdull建议的那样,Spring确实提供了一个 HttpMessageConverter 实现资源本身包含 InputStream ResourceHttpMessageConverter 。它不支持所有资源类型,但由于你应该编程接口,你应该只使用超级接口资源

As Abdull suggests, Spring does come with an HttpMessageConverter implementation for Resource which itself wraps an InputStream, ResourceHttpMessageConverter. It doesn't support all Resource types, but since you should be programming to interfaces anyway, you should just use the superinterface Resource.

当前的实现(4.3.5)将返回 ByteArrayResource ,其中包含回复内容流复制到您可以访问的新 ByteArrayInputStream

The current implementation (4.3.5), will return a ByteArrayResource with the content of the response stream copied to a new ByteArrayInputStream which you can access.

您不必关闭流。 RestTemplate 为您处理。 (如果您尝试使用 InputStreamResource ResourceHttpMessageConverter 支持的另一种类型,因为它包装了底层响应的 InputStream 但在它暴露给您的客户端代码之前就已关闭。)

You don't have to close the stream. The RestTemplate takes care of that for you. (This is unfortunate if you try to use a InputStreamResource, another type supported by the ResourceHttpMessageConverter, because it wraps the underlying response's InputStream but is closed before it can be exposed to your client code.)

这篇关于使用RestTemplate获取InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆