Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javaservlet:从url获取图像并显示它_Java_Servlets - Fatal编程技术网

Javaservlet:从url获取图像并显示它

Javaservlet:从url获取图像并显示它,java,servlets,Java,Servlets,我如何从URL抓取图像,然后显示它。。。就像代理一样 我想我需要首先将图像获取到文件流,然后输出文件。代码如下: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // temporarily hard-code the image String imageUrlStri

我如何从URL抓取图像,然后显示它。。。就像代理一样

我想我需要首先将图像获取到文件流,然后输出文件。代码如下:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // temporarily hard-code the image
        String imageUrlString = "http://i.imgur.com/3lQAD2E.jpg";

         // Read the image ...
        URL urlConn = new URL(imageUrlString);
        InputStream inputStream      = urlConn.openStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte [] buffer               = new byte[ 1024 ];

        int n = 0;
        while (-1 != (n = inputStream.read(buffer))) {
           output.write(buffer, 0, n);
        }
        inputStream.close();

        // Here's the content of the image...
        byte [] data = output.toByteArray();

        PrintWriter out = response.getWriter();
        out.print(data);     
    }  
但是,返回的只是一个损坏的图像文件。

您应该使用而不是编写器。作者处理字符数据。此外,您可能希望了解回复