Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to set HttpURLConnection timeout while reading a stream?

807588Jul 28 2009
I want it got time out if the connection if lose while i read a stream from URL
try {
	int timeout = 700;
	HttpURLConnection connection = (HttpURLConnection) downloadURl.openConnection();
	connection.setConnectTimeout(timeout);
	connection.setRequestProperty("Range","bytes=" + downloaded + "-");

	connection.connect();
	if (connection.getResponseCode() / 100 != 2) {
		error();
	}

	int contentLength = connection.getContentLength();
	if (contentLength < 1) {
		error();
	}

	if (status == DOWNLOADING){
		if (size == -1) {
			size = contentLength;
		}

		file = new RandomAccessFile(saveTmpName+".tmp", "rw");
		file.seek(downloaded);
	}

	byte buffer[];
	stream = connection.getInputStream();
connection.setReadTimeout(timeout);
	while (status == DOWNLOADING) {  
		if (size - downloaded > MAX_BUFFER_SIZE) {
			buffer = new byte[MAX_BUFFER_SIZE];
		} else {
			buffer = new byte[(int)(size - downloaded)];
		}


		int read = stream.read(buffer); // how to set timeout while it is reading stream
		if (read <= 0)
			break;

		file.write(buffer, 0, read);
		downloaded += read;
	}

	if (status == DOWNLOADING) {
		status = COMPLETE;
	}
				
} catch (SocketTimeoutException  e) {
	error();
} catch (IllegalArgumentException e) {
	error();
} catch (Exception e) {
	error();
} finally {
	if (file != null) {
		try {
			file.close();
		} catch (Exception e) {}
	}

	if (stream != null) {
		try {
			stream.close();
		} catch (Exception e) {}
	}
}
I try to set "setReadTimeout()" but is still not through timeout Exception
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 25 2009
Added on Jul 28 2009
0 comments
707 views