Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection.getInputStream() blocks

Tags:

java

I'm using the HttpURLConnection class to make http requests. My code looks something like this-

while(true){
    try{
         connection=(HttpURLConnection)url.openConnection();
         connection.setDoOutput(true);
         connection.setConnectTimeout(2*1000);
         InputStream in=connection.getInputStream();
    }
    catch(SocketTimeOutException e){}
    catch(IOException e){}
}

I do some processing on the data once I retrieve the InputStream object. My problem is that if I let the program run long enough, the call to getInputStream blocks and I never get past that.

Am I missing something? Any pointers or help would be greatly appreciated. Thanks.

like image 289
Sandman Avatar asked May 22 '12 15:05

Sandman


People also ask

What does connection getInputStream do?

Calling getInputStream() signals that the client is finished sending it's request, and is ready to receive the response (per HTTP spec). It seems that the URLConnection class has this notion built into it, and must be flush()ing the output stream when the input stream is asked for.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

What is the use of HttpURLConnection in Java?

HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol.


1 Answers

Set the read time out for the connection. Also, close the streams in a finally block once you're done with them.

like image 174
Zaki Avatar answered Oct 26 '22 17:10

Zaki