【问题标题】:Java Android, HttpURLConnection blocks when trying connect to a host which not exist尝试连接到不存在的主机时,Java Android,HttpURLConnection 阻塞
【发布时间】:2013-11-16 11:46:44
【问题描述】:

我正在android上编写一个应用程序,它将从互联网上下载一张图片。 当我测试下载模块时,我发现了这个奇怪的事情,当我让 HttpURLConnection 尝试连接到一个不存在的主机时,尽管我设置了超时参数,但它只是阻塞在那里。

代码在这里:

            String[] ext = link.split("\\.");
            String extension = ext[ext.length-1];
            String filePath = Environment.getExternalStorageDirectory()+ File.separator+appInfo.getState(AppInfo.STORE_IMAGE)+File.separator;
            String fileName = id+"."+extension;
            File file = new File(filePath+fileName);

            URL url = new URL(link);
            URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
            url = uri.toURL();
            link = url.toString();

            Log.i("link", link);

            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;

            try {
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(2000);
                connection.setReadTimeout(2000);
                connection.connect();
            } catch (java.net.SocketTimeoutException e) {
                throw new Exception("timeout");
            } catch (java.io.IOException e) {
                throw new Exception("timeout");
            }

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();

            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream(filePath+fileName);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
            }

它不会返回或抛出异常。

在 DBMS 中,我可以在阻塞几分钟后看到一个错误。 当我让它连接到现有主机时,它会很快返回错误。

【问题讨论】:

    标签: java android httpurlconnection


    【解决方案1】:

    此代码不会阻塞。当您尝试在空连接上设置连接超时时,它会抛出 NullPointerException。

    【讨论】:

    • 哦,对不起,我已经编辑了上面的代码,但还是有同样的问题。
    • 您需要修复您的异常处理。您正在抑制实际异常并记录您自己的设计之一。您需要记录您得到的实际异常。它会说明一切。
    猜你喜欢
    • 2011-03-13
    • 2023-04-09
    • 1970-01-01
    • 2013-06-08
    • 2013-07-08
    • 1970-01-01
    • 2014-04-24
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多