Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.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
Java 从URL读取InputStream并通过Servlet编写_Java_Url_Servlets_Response_Inputstream - Fatal编程技术网

Java 从URL读取InputStream并通过Servlet编写

Java 从URL读取InputStream并通过Servlet编写,java,url,servlets,response,inputstream,Java,Url,Servlets,Response,Inputstream,我正在尝试编写一个InputStream,它是通过Servlet的doGet方法从URL获得的。这是我的密码: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestedUrl = request.getParameter("url"); if (StringUtils.isN

我正在尝试编写一个
InputStream
,它是通过
Servlet
doGet
方法从
URL
获得的。这是我的密码:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String requestedUrl = request.getParameter("url");

    if (StringUtils.isNotBlank(requestedUrl)) {
        ReadableByteChannel inputChannel = null;
        WritableByteChannel outputChannel = null;

        try {
            URL url = new URL(requestedUrl);
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            int responseCode = httpConnection.getResponseCode();

            System.out.println(responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                response.setContentType("image/jpg");
                httpConnection.connect();
                InputStream imageStream = url.openStream();
                OutputStream outputStream = response.getOutputStream();

                inputChannel = Channels.newChannel(imageStream);
                outputChannel = Channels.newChannel(outputStream);
                ByteBuffer buffer = ByteBuffer.allocate(10240);

                while (inputChannel.read(buffer) != -1) {
                    buffer.flip();
                    outputChannel.write(buffer);
                    buffer.clear();
                }
            }
        } catch (Exception ex) {
            Log.error(this, ex.getMessage(), ex);
        } finally {
            if (ObjectUtils.notEqual(outputChannel, null)) {
                try {
                    outputChannel.close();
                } catch (IOException ignore) {
                }
            }

            if (ObjectUtils.notEqual(inputChannel, null)) {
                try {
                    inputChannel.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
}
我可以在控制台中看到,
响应代码
是200,但它没有在页面中写入任何内容。在Firefox中,我得到:

形象 “上下文\u root/dam/no image-aware servlet?url=http%3A//localhost%3A80/file/MHIS044662&Rendition=164FixedWidth&noSaveAs=1” 无法显示,因为它包含错误


我找不到我做错了什么。任何指针都会非常有用。

我已经尝试对您的代码进行了一些修改,以解决
getResponseCode()
connect()
的错误顺序以及其他一些小问题

特别是,如果出现问题(例如,在其他服务器上找不到文件、IOException、非法URL等),请确保始终返回错误状态代码(2xx除外),否则浏览器始终会获得200-正常,但没有数据

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String requestedUrl = request.getParameter("url");

    if (StringUtils.isBlank(requestedUrl)) {
        // TODO: send error code 400 - Bad Request
        return;
    }

    try {
        URL url = new URL(requestedUrl);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        response.setContentType("image/jpg");
        httpConnection.connect();

        int responseCode = httpConnection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // TODO: set correct content type to response

            OutputStream outputStream = response.getOutputStream();

            try (InputStream imageStream = url.openStream()) {
                IOUtils.copy(imageStream, outputStream );
            }
        } else {
            // TODO: send error code (depends on responseCode), probably 500
        }
    } catch (Exception ex) {
        Log.error(this, ex.getMessage(), ex);
        // TODO: send error code 400 if malformed url
        // TODO: send error code 404 if image not found (responseCode == 404)
        // TODO: send error code 500 else
    }
    // Don't close the response-OutputStream! You didn't open it either!
}

你能在httpConnection.connect()之前使用响应代码吗?@Taylor我不确定我能抓住你。您的意思是在httpConnection.getResponseCode()之前调用
httpConnection.connect()
;?对如果您在连接之前有响应代码,我会感到惊讶。@TapasBose getResponseCode()仅在您之前执行httpConnection.connect()时返回有用的内容。您是否为响应设置了正确的内容类型?