HttpURLConnection类和没有互联网 [英] HttpURLConnection and no internet

查看:162
本文介绍了HttpURLConnection类和没有互联网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道如果我碰上这是第一个,但我会在这里发布,以节省时间某人。好了,玩弄和尝试HttpURLConnection类做于Android的一些HTTP请求我想知道如果我用互联网用它在我的手机被禁用会发生什么了。我无意中发现了一个有趣的错误:

Don't know if I'm the first one to run into this, but I'll post it here to save someones time. Ok, so after playing around and trying out HttpURLConnection to do some HTTP requests from Android I wondered what would happen if I used it with Internet on my phone disabled. I've stumbled on an interesting bug:

    URL url = new URL("http://google.com");
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setReadTimeout(15000);
    try {
        InputStream in = new BufferedInputStream(c.getInputStream());
        httpResult = readStream(in);
    } catch (IOException e) {
        Log.e(TAG, "Error: ", e);

    } finally {
        c.disconnect();
    }

如果我运行这个code与Internet我的手机上禁用一个IOException获取与否堆栈跟踪任何发现。什么是happenning?

If I run this code with Internet disabled on my phone an IOException gets caught with no stacktrace whatsoever. What's happenning?

推荐答案

于是经过一番周围挖我发现IOException的一个子类实际上是被抛出:的UnknownHostException 。对于HttpURLConnection.getInputStream()和HttpURLConnection.connect()Android文档无话可说了。

So after some digging around I found that a subtype of IOException is actually being thrown: UnknownHostException. Android documentation for HttpURLConnection.getInputStream() and HttpURLConnection.connect() say nothing about it.

这篇关于HttpURLConnection类和没有互联网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆