等待但没有抛出SocketTimeoutException?

时间:2012-02-04 10:25:25

标签: android httpurlconnection socket-timeout-exception

我正在编写一个从服务器接收数据的Android应用程序。理论上没有互联网连接所以我试图通过捕获SocketTimeoutException以显示错误消息,重试屏幕或其他东西来捕获这种情况。不幸的是,不会抛出此异常。至少它没有跳进catch子句。我做错了什么?

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
    }
}

1 个答案:

答案 0 :(得分:1)

您还需要设置连接超时。 Please see this documentation.

由于终点不存在,如果没有设置连接超时,连接永远不会超时。

  

setConnectTimeout(int timeout)设置超时值(以毫秒为单位)   用于建立与指向的资源的连接   此URLConnection实例。