【问题标题】:How to avoid to Time out Exception?如何避免超时异常?
【发布时间】:2015-12-11 07:24:19
【问题描述】:

我正在尝试创建一个依赖于 JSON 响应的 android 应用程序。有时服务器需要很长时间才能响应并以超时异常结束。因此,我想添加一个限制,例如如果没有响应,我的 web 服务调用应该在 20 秒后中止。你能帮我实现这个想法吗?

提前致谢。

【问题讨论】:

  • 您是否尝试过使用像 Volley 这样的优秀网络库?
  • HttpConnectionParams.setConnectionTimeout(httpParams, 20000);

标签: android json eclipse connection timeout


【解决方案1】:

您没有提供有关实际实现的太多细节。

但是,弄乱超时似乎是对应该修复的潜在问题的紧急修复。

但是,使用 websocket 进行传输可能是一种可能(而且可能更优雅)的解决方案。一旦创建,它们就会在客户端和服务器之间提供持久连接。

Using websockets on Android and IOS

【讨论】:

    【解决方案2】:

    有几种方法可以实现目标。

    我们可以使用HttpURLConnection来做http请求。

    public String doPost() {
        if (!mIsNetworkAvailable) {
            return null;
        }
    
        try {
            URL url = new URL(mURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            for (String key : mHeadersMap.keySet()) {
                conn.setRequestProperty(key, mHeadersMap.get(key));
            }
            conn.setRequestProperty("User-Agent", "Android");
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.getOutputStream().write(mContent);
            conn.getOutputStream().flush();
            int rspCode = conn.getResponseCode();
            if (rspCode >= 400) {
                return null;
            }
    
            byte[] buffer = new byte[8 * 1024];
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            while ((len = bis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            final String result = new String(baos.toByteArray());
            baos.close();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    

    setConnectTimeout :设置连接时等待的最长时间(以毫秒为单位)。

    setReadTimeout:设置在放弃之前等待输入流读取完成的最长时间。

    参考:http://developer.android.com/reference/java/net/URLConnection.html

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 2010-09-29
      • 2018-07-21
      • 2016-09-15
      相关资源
      最近更新 更多