我正在尝试在 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));
获取 UnknownHostException
的完整堆栈跟踪和Log.e(tag, "Exception Host", ex);
方法。
只有 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 的浏览器打开网站时,它打开时没有错误。
最佳答案
堆栈跟踪的原因在 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();
关于java - 无法在 android 中获取 `java.net.UnknownHostException` 的堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35571278/