Search code examples
androidhttpurlconnectionsocket-timeout-exception

SocketTimeoutException awaited but not thrown?


I'm writing an Android app which receives data from a server. Theoretical there could not be an internet connection so I try to catch this case by catching a SocketTimeoutException to show an error message an a retry screen or something else. Unfortunately this exception won't be thrown. At least it doesn't jump into the catch clause. What am I doing wrong?

public class HttpConnector {

    private String urlString;
    private int connectionTimeout = 5000; //milliseconds

    public HttpConnector(String urlString)  {
        this.urlString = urlString;
    }

    public String receiveData() throws PolizeiwarnungException {
        URL url = null;
        HttpURLConnection urlConnection = null;
        StringBuffer b = new StringBuffer();

        try {
            url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(connectionTimeout);
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); //Here it gets stuck if there is no connection to the server

            String str;
            while ((str = reader.readLine()) != null) {
                b.append(str + "\n");
            }
        }
        catch (SocketTimeoutException e) {
            //TODO
            e.printStackTrace();
        }
        catch (IOException e) {
            throw new PolizeiwarnungException(e);
        } 
        finally {
            if (urlConnection != null)  {
                urlConnection.disconnect();
            }
        }

        return b.toString();
    }

    public void sendData(String data)  {
        //TODO
    }
}

Solution

  • You need to also set the connect timeout. Please see this documentation.

    Since the end point does not exist, without having set a connect time out the connection will never time out.

    setConnectTimeout(int timeout) Sets the timeout value in milliseconds for establishing the connection to the resource pointed by this URLConnection instance.