2

I am working on an Android app that needs to read a line from a web page right when it starts. I am doing this with the following code:

try{
        URL url = new URL("http://www.example.com");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        line = reader.readLine();
}
catch(Exception e){
        e.printStackTrace();
}

It is working fine, but sometimes the connection or the server are slow, and the app freezes or crashes.

I want to put a timeout of 5 seconds, and should it reach that timeout I want to show a toast to the user saying the network is busy, asking him to try again later.

I tried the HttpURLConnection setConnectTimeout() method but it didn't work.

Any clues how I can achieve this? Thanks forehand.

2 Answers 2

3

Probably better solution if you setConnectionTimeout to 5 sec, catch SocketTimeoutException and show Toast from there. When you set ConnectionTimeout to some value and connection didn't get response code will throw SocketTimeoutException. Here you can catch it and call handler to show a toast in UI. Finally will close the connection and release memory.

class MyHttpClient extends DefaultHttpClient {
    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", 
            mSSLSocketFactory != null 
            ? mSSLSocketFactory 
            : SSLSocketFactory.getSocketFactory(), 
            443));

    return new SingleClientConnManager(getParams(), registry);
}

   MyHttpClient httpClient = new MyHttpClient();

    // set http params
    HttpParams params = httpClient.getParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(30000));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(30000));
    httpClient.setParams(params);

    ....
    httpClient.execute(httpUriRequest) 
Sign up to request clarification or add additional context in comments.

3 Comments

OK, but I am guessing I need to set the timeout before I call the "HttpURLConnection con = (HttpURLConnection) url.openConnection();" line, right? Cause I guess that line actually performs the connection?
@DanielS Ask more if something doesn't work I will update with more details.
@Maxim.. you have any idea about this stackoverflow.com/questions/16996820/…
1

Consider using AndroidHttpClient class instead, it has nice preset timeouts so you wouldn't have to do anything.

Comments

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.