1

我正在编写一个从服务器接收数据的 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
    }
}
4

1 回答 1

1

您还需要设置连接超时。请参阅此文档。

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

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

于 2012-02-04T11:26:18.423 回答