1

I am trying to get some data from remote server. To achieve this I use HttpURLConnection. The problem is that sometimes the server after connection is established just hangs or what, doesn't close connection, and I hang there. Also that hanged thread acquired the lock, so all all other threads are just sucking :D Code:

try {
        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName(CharEncoding.UTF_8)));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {

Last line is where we are hanging. I found method setConnectTimeout(timeout), but seems this is not the case because it is timeout before connection is established. What is common way to solve such situations?

3
  • timeout before the connection established? then you wouldn't come all the way down to the while loop, or am I misunderstanding something?? Commented Dec 19, 2011 at 15:49
  • Sorry, I has wrote not clear here.I meant found such method in class HttpURLConnection ;) No time outs were in my code .. Commented Dec 20, 2011 at 10:09
  • no worries I'm glad if I could help solve out the problem whatever it was :) Commented Dec 20, 2011 at 10:18

1 Answer 1

3

assuming you meant timeout after the connection is established (likely during the read), how about something like this

URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(c_timeout);
urlConnection.setReadTimeout(r_timeout);
stream = urlConnection.getInputStream();
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I didn't find this method. Seems read timeout will solve this issue. Thanks! Will try tommorow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.