如何从服务器下载图像,然后将其作为响应写入我的servlet中。 保持良好表现的最佳方法是什么?
这是我的代码:
JSONObject imageJson;
... //getting my JSON
String imgUrl = imageJson.get("img");
答案 0 :(得分:2)
如果你不需要隐藏你的图像源,并且如果服务器也可以从客户端访问,我只是将你的响应指向远程服务器(因为你已经有了url)=>您不需要先下载到您的服务器,但可能客户端可以直接访问它=>你不要浪费你的资源。
但是,如果您仍然需要先将其下载到您的服务器,以下帖子可能有所帮助:Writing image to servlet response with best performance
答案 1 :(得分:1)
避免在servlet中对图像进行中间缓冲非常重要。相反,只需将收到的内容流式传输到servlet响应:
InputStream is = new URL(imgUrl).openStream();
OutputStream os = servletResponse.getOutputStream();
IOUtils.copy(is, os);
is.close();
我正在使用来自Apache Commons的IOUtils
(不是必需的,但很有用)。
答案 2 :(得分:0)
完整的解决方案:下载地图并保存到文件。
String imgUrl = "http://maps.googleapis.com/maps/api/staticmap?center=-15.800513,-47.91378&zoom=11&size=200x200&sensor=false";
InputStream is = new URL(imgUrl).openStream();
File archivo = new File("c://temp//mapa.png");
archivo.setWritable(true);
OutputStream output = new FileOutputStream(archivo);
IOUtils.copy(is, output);
IOUtils.closeQuietly(output);
is.close();