有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

json java下载,然后将图像作为servlet响应写入

如何从服务器下载图像,然后将其作为响应写入我的servlet。 保持良好性能的最佳方法是什么

这是我的密码:

JSONObject imageJson;
... //getting my JSON
String imgUrl = imageJson.get("img");

共 (3) 个答案

  1. # 1 楼答案

    如果您不需要隐藏图像源,并且客户端也可以访问服务器,我只需要将您的响应指向远程服务器(因为您已经有了url)=>;您不需要先下载到服务器,但客户端可能可以直接访问它=>;你不会浪费你的资源

    不过,如果您仍然需要先将其下载到服务器上,下面的帖子可能会有所帮助:Writing image to servlet response with best performance

  2. # 2 楼答案

    完整的解决方案:下载地图并保存到文件

        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();
    
  3. # 3 楼答案

    在servlet中避免图像的中间缓冲非常重要。相反,只需将接收到的内容流式传输到servlet响应:

    InputStream is = new URL(imgUrl).openStream();
    OutputStream os = servletResponse.getOutputStream();
    
    IOUtils.copy(is, os);
    is.close();
    

    我正在使用Apache Commons中的^{}(不是必需的,但很有用)