Java Android,HttpURLConnection在尝试连接到不存在的主机时会阻塞

时间:2013-11-16 11:46:44

标签: java android httpurlconnection

我在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中,我可以在阻止后几分钟看到错误。 当我将它连接到一个存在的主机时,它会很快返回错误。

1 个答案:

答案 0 :(得分:0)

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