Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Set Timeout with URL/URLConnection

Status
Not open for further replies.

jlipsitz

Programmer
Jul 13, 2003
14
US
Hi

I am using the URL class, but am having trouble while reading in from the input stream. I am using readLine to read from the stream, but with some pages I do not come out of the loop. Is there any way to set a timeout so that after some period of time the stream will close automatically?

Thanks
 
It would be simple to do it like so ...

Code:
long start = System.currentTimeMillis();
long end = 20000; // millis

while ((System.currentTimeMillis() - start) < 20000) {
    // do the readLine()
}

 
if you're waiting for a line to be ready, you can do something like the following (which is a slightly modified version of sedj's code):<br><br><FONT FACE=monospace>URLConnection con = myURL.openConnection();<br>int size = con.getContentLength();<br>BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));<br>while (/* entire output is less than 'size' */) {<br>&nbsp;&nbsp;&nbsp;&nbsp;long start = System.currentTimeMillis();<br>&nbsp;&nbsp;&nbsp;&nbsp;while (!myBufferedReader.ready()) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (System.currentTimeMillis() - start) &lt; 20000) return;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp;&nbsp;String nextLine = myBufferedReader.readLine();<br>}<br>in.close();</font><br><br>not sure if you're using a different method of finding if you've reached the end of the InputStream... not sure if there is one, I'd be interested if there is. <p>Liam Morley<br><A HREF="mailto:"></A><br>&quot;light the deep, and bring silence to the world.<br>light the world, and bring depth to the silence.&quot;
 
akk. of course you'd want to modify my above code to not simply return, but break out of the outer while loop (using labels). but that should be a start. if you're not sure how to break out of an outer loop let me know and i'll repost a corrected version of the code.<br><br>also, my above code returns the first time around... of course you want to flip the 'less-than' sign to a 'greater-than' sign so that it only exits if you've been waiting longer than a specified time duration. (i just used sedj's working example of 20 secs.) <p>Liam Morley<br><A HREF="mailto:"></A><br>&quot;light the deep, and bring silence to the world.<br>light the world, and bring depth to the silence.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top