简体   繁体   English

如何使用httpurlconnection从InputStream读取时设置超时?

[英]How to set a timeout while reading from InputStream using httpurlconnection?

I have a java application in which I download files using HttpURLConnection. 我有一个java应用程序,我在其中使用HttpURLConnection下载文件。 I set 15 Seconds in connect timeout and 1 hour in read timeout properties. 我在连接超时中设置了15秒,在读取超时属性中设置了1小时。 As per my understanding, if file on server is big enough to take more than 1 hour to download, it will fail with timeout exception. 根据我的理解,如果服务器上的文件足够大,下载时间超过1小时,则会因超时异常而失败。 Works fine. 工作良好。 The problem is, when I pull the Internet cable out from the client machine while download is in progress(reading buffer from InputStream), the download process does not terminates immediately, it takes 1 hour (read timeout) to break the download. 问题是,当我在下载过程中从客户端计算机拔出Internet电缆(从InputStream读取缓冲区)时,下载过程不会立即终止,需要1小时(读取超时)来中断下载。 Is there any way I can terminate the download process? 有什么办法可以终止下载过程吗? Following is the source code: 以下是源代码:

public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
public static void downloadFile(String fileURL, String saveDir)
            throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setConnectTimeout(15*1000);
        httpConn.setReadTimeout(60*60*1000);
        int responseCode = httpConn.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                        fileURL.length());
            }

            System.out.println("Content-Type = " + contentType);
            System.out.println("Content-Disposition = " + disposition);
            System.out.println("Content-Length = " + contentLength);
            System.out.println("fileName = " + fileName);

            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + File.separator + fileName;

            // opens an output stream to save into file
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) { //This is where the download gets stuck on some connection issues 
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("File downloaded");
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }
}

As per my understanding, if file on server is big enough to take more than 1 hour to download, it will fail with timeout exception. 根据我的理解,如果服务器上的文件足够大,下载时间超过1小时,则会因超时异常而失败。

No. If the server fails to respond to any single read request for over an hour, it will fail. 不可以。如果服务器在一个多小时内没有响应任何单个读取请求,它将失败。 The timeout starts when you call read() , and ends when a response to that read is received or the timeout period expires. 当您调用read()时超时开始,并在收到对该读取的响应或超时时间到期时结束。 Then it starts again next read. 然后它再次开始下一次读取。 Total time has nothing to do with it. 总时间与它无关。 You've misunderstood completely. 你完全误解了。

Works fine. 工作良好。

Works fine but not as you described. 工作正常但不如你所描述的那样。

The problem is, when I pull the Internet cable out from the client machine while download is in progress(reading buffer from InputStream), the download process does not terminates immediately, it takes 1 hour (read timeout) to break the download. 问题是,当我在下载过程中从客户端计算机拔出Internet电缆(从InputStream读取缓冲区)时,下载过程不会立即终止,需要1小时(读取超时)来中断下载。

That's exactly what it's supposed to do, as described above. 如上所述,这正是它应该做的事情。

Is there any way I can terminate the download process? 有什么办法可以终止下载过程吗?

Set a shorter timeout. 设置较短的超时。 Set it long enough so the server should respond within that interval, and short enough hat a cable pull doesn't take too long to time out. 设置它足够长,以便服务器应该在该间隔内响应,并且足够短的电缆拉动不需要太长时间才能超时。 An hour is too long. 一个小时太长了。 Try a few minutes. 试试几分钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Google App Engine中从HttpURLConnection读取数据时发生超时异常 - Timeout exception while reading data from HttpURLConnection in Google App Engine 从Servlet请求输入流读取时套接字超时 - Socket Timeout while reading from Servlet request inputstream 从 HttpURLConnection 获取 InputStream 对象时出现 FileNotFoundException - FileNotFoundException while getting the InputStream object from HttpURLConnection 使用Scanner时使用InputStream进行读取 - Reading with InputStream while using Scanner HTTPUrlConnection错误(从inputStream读取后无法打开OutputStream) - HTTPUrlConnection error (Can't open OutputStream after reading from an inputStream) 从InputStream读取时发生IOException - IOException while reading from InputStream 从android中的HttpURLConnection获取InputStream时获取UnknownLengthHttpInputStream - Getting UnknownLengthHttpInputStream while getting InputStream from HttpURLConnection in android 为什么 BufferedInputStream(InputStream in, int bufSize) 在使用 mark() 时没有从 inputStream 中读取 bufSize 块中的数据? - Why BufferedInputStream(InputStream in, int bufSize) is not reading data in chunks of bufSize from the inputStream while using mark()? 如何设置InputStream.read的读取超时? - How to set the read timeout for InputStream.read? 来自HttpURLConnection的InputStream:何时断开连接? - InputStream from HttpURLConnection: When to disconnect?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM