Sandman
Sandman

Reputation: 5580

HttpURLConnection.getInputStream() blocks

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.

Upvotes: 8

Views: 13615

Answers (2)

Nurlan
Nurlan

Reputation: 615

You should close connections that are not used. Here is example:

connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(2*1000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
 stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
reader.close();

Upvotes: 1

Zak
Zak

Reputation: 7078

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

Upvotes: 7

Related Questions