Download URL content with timeout
I want to download the URL content in java with a specified download time. For ex: i want to have a maximum download timeout of 10 seconds for www.yahoo.com. If download takes more than 10s, then an error should be thrown. I have written the code for opening a connection and downloading the entire contents. But how do i set the download timeout? Here is the code snippet:
StringBuilder text = new StringBuilder();
urlconn = (HttpURLConnection)url.openConnection();
urlconn.setConnectTimeout(100000);
//urlconn.setInstanceFollowRedirects(false);
urlconn.setRequestMethod("GET");
urlconn.connect();
buf = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
while((line = buf.readLine()) != null)
text开发者_StackOverflow中文版.append(line);
System.out.println(url + "=> "+ urlconn.getResponseCode());
You can set it by URLConnection#setReadTimeout()
.
urlconn.setReadTimeout(10000); // 10 sec
// ...
Use URLConnection.setReadTimeOut()
.
精彩评论