【问题标题】:java.net.UnknownHostException: Unable to resolve host "google.com"java.net.UnknownHostException:无法解析主机“google.com”
【发布时间】:2013-01-06 02:33:45
【问题描述】:

我在 Galaxy Tab (v1) 上运行我的应用程序。
我已经添加了

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

许可。

我正在使用以下代码检查网站是否在线:

public boolean checkIfSite(final String url) {
    Data.isUp = false;

    new Thread(new Runnable() {
        public void run() {
            try {
                Data.isUp = InetAddress.getByName("google.com").isReachable(25000);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
    return Data.isUp;
}

我运行它并抛出异常:

01-05 19:15:04.007: W/System.err(3303): java.net.UnknownHostException: Unable to resolve host "google.com": No address associated with hostname
01-05 19:15:04.007: W/System.err(3303):     at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
01-05 19:15:04.007: W/System.err(3303):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
01-05 19:15:04.007: W/System.err(3303):     at java.net.InetAddress.getByName(InetAddress.java:295)
01-05 19:15:04.007: W/System.err(3303):     at com.sonyericsson.extras.liveview.plugins.sandbox.SandboxPluginService$2.run(SandboxPluginService.java:184)
01-05 19:15:04.007: W/System.err(3303):     at java.lang.Thread.run(Thread.java:856)
01-05 19:15:04.007: W/System.err(3303): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
01-05 19:15:04.011: W/System.err(3303):     at libcore.io.Posix.getaddrinfo(Native Method)
01-05 19:15:04.011: W/System.err(3303):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
01-05 19:15:04.011: W/System.err(3303):     at java.net.InetAddress.lookupHostByName(InetAddress.java:411)
01-05 19:15:04.011: W/System.err(3303):     ... 4 more

【问题讨论】:

  • 你的方法根本就坏了;您在线程运行之前返回值。如果您等待线程,您将冻结您的应用程序,这正是您应该避免的。您需要使用回调或承诺。
  • 我要在它运行之前返回它?我.start()它,然后在它关闭后它返回
  • 没有。你.start() 然后你立即返回
  • 有人遇到过类似的问题; stackoverflow.com/questions/2096874/…

标签: android unknown-host


【解决方案1】:

您是否尝试过使用 http://google.com 而不仅仅是 google.com?

正如@SLaks 所说,您的方法是错误的,因为您在启动线程后返回,需要使用回调(类似于您在 iOS 中对委托执行的操作)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2013-09-07
    相关资源
    最近更新 更多