【问题标题】:Unable to get stack trace of `java.net.UnknownHostException` in android无法在android中获取`java.net.UnknownHostException`的堆栈跟踪
【发布时间】:2016-02-23 07:27:22
【问题描述】:

我正在尝试在android中获取主机名为nirranjan-pc的机器的IP地址,并尝试按照this问题的答案使用下面的代码

Log.e(tag, "In background method :: ");
try {
    String ip = InetAddress.getByName("nirranjan-pc").getHostAddress();
    Log.e(tag, "++++++++++++ IP FOUND :: " + ip);
} catch (Exception ex) {
    Log.e(tag, "Exception:: " + ex);
    Log.e(tag, Log.getStackTraceString(ex));
    Log.e(tag, "Exception Host ", ex);
} finally {
    Log.e(tag, "Finally::");
}

但我没有获得 IP 地址,并且无法使用 Log.e(tag, Log.getStackTraceString(ex));Log.e(tag, "Exception Host ", ex); 方法获得 UnknownHostException 的完整堆栈跟踪。

只有Log.e(tag, "Exception:: " + ex); 方法可以正常工作。

我的 logcat 在下面。

02-23 12:23:24.308 16507-16618/in.gauriinfotech.sevadeal E/Favour: In background method :: 
02-23 12:23:24.350 16507-16513/in.gauriinfotech.sevadeal W/art: Suspending all threads took: 14.457ms
02-23 12:23:24.377 16507-16618/in.gauriinfotech.sevadeal E/Favour: Exception:: java.net.UnknownHostException: Unable to resolve host "nirranjan-pc": No address associated with hostname
02-23 12:23:24.380 16507-16618/in.gauriinfotech.sevadeal E/Favour: Exception Host 
02-23 12:23:24.380 16507-16618/in.gauriinfotech.sevadeal E/Favour: Finally::

我的问题

1) 为什么Log.e(tag, Log.getStackTraceString(ex));Log.e(tag, "Exception Host ", ex); 方法不能正常运行并且没有给出堆栈跟踪。

2) 我在 java 桌面应用程序中获得了正确的 IP 地址,没有任何错误。为什么它在android中不起作用?

-- 我也尝试在 android 中使用 Google Chrome 浏览器访问相同

使用 IP 地址可以正常工作

但不能使用机器名称

奇怪的是,当我尝试从 Windows Phone 的浏览器打开网站时,它打开时没有错误。

【问题讨论】:

    标签: java android


    【解决方案1】:

    您的堆栈跟踪的原因在于 Log 类的来源。
    UnknownHostException 异常不打印

    如果您检查代码,您可以看到 Log.getStackTraceString() 方法已在 ICS 中进行了修补,以在 UnknownHostException 的情况下返回空的 String

    这里是relevant code

    //To reduce the amount of log spew that apps do in the non-error
    // condition of the network being unavailable.
    
    Throwable t = tr;
    while (t != null) {
        if (t instanceof UnknownHostException) {
            return "";
        }
     t = t.getCause();
    

    【讨论】:

      【解决方案2】:

      关于您的第一个问题,请尝试Throwable.printStackTrace(PrintWriter pw) 获取堆栈跟踪,例如:

      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      ex.printStackTrace(pw);
      Log.e(tag, sw.toString());
      

      对于您的第二个问题,可能是您的 DNS 配置不正确,无法查找主机名并将其转换为正确的 IP。

      编辑:

      第二个问题也请看这里Android Browser hostnames does not get resolved if domain name is not appended

      【讨论】:

      • 我检查了问题和答案..这意味着无法使用机器名而不是IP地址打开连接.??
      • @ELITE 机器名的使用通常由 NetBIOS 或 Zeroconf 协议使用,这显然没有在 android 中实现。如果你想使用名称而不是 IP,你可以在你的机器上使用一个简单的 dns 服务器
      猜你喜欢
      • 2015-06-15
      • 1970-01-01
      • 2010-10-11
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多