android - 等待但未抛出 SocketTimeoutException?

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

最佳答案

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

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

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

关于android - 等待但未抛出 SocketTimeoutException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9140143/

相关文章:

linux - Karma/PhantomJS 在 Windows 上工作,在 Linux 上相同的配置无法向 PhantomJS 发送消息

android - EditText 被 Keyboard 覆盖

javascript - 如何在Android上转换手机网页?

java - 带有图像/jpeg 的 Android HttpURLConnection POST 请求

java - 使用 HTTPUrlConnection 时出现 StackOverflowError

java - 从 S3 下载大于 3Gb 的文件失败并显示 "SocketTimeoutException: Read timed out"

安卓快速搜索

java - 在 PreviewFrame 上使用 Zxing 库实现增强现实

java - 我正在尝试检查网站状态是否在线