【问题标题】:SocketTimeoutException awaited but not thrown?SocketTimeoutException 等待但未抛出?
【发布时间】:2012-02-04 10:25:24
【问题描述】:

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

【问题讨论】:

    标签: android httpurlconnection socket-timeout-exception


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-04
      • 2015-08-14
      • 2016-08-09
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多