Networking code sometimes throws UnknownHostException

ぐ巨炮叔叔 提交于 2019-11-26 10:03:12

问题


I am trying to data from a server. Sometimes my code fails due to an UnknownHostException. Why is that? What is the cause of this problem?


回答1:


This may occur if a hiccup in DNS server has occurred. Apart from making the DNS server more robust or looking for another one, you can also just use the full IP address instead of the hostname. This way it doesn't need to lookup the IP address based on the hostname. However, I would rather fix the DNS issue and prefer the DNS since IP addresses may change from time to time.




回答2:


An UnknownHostException indicates the host specified couldn't be translated to an IP address. It could very well be a problem with your DNS server.




回答3:


If the DNS resolution fails intermittently, catch the exception and try again until you get name resolution. You can only control, what you can control... And if you can't control/fix the DNS server, make your app robust enough to handle the quirky DNS server.




回答4:


I too am seeing sporadic UnknownHostExceptions in Java for no apparent reason. The solution is just to retry a few times. Here is a wrapper for DocumentBuilder.parse that does this:

static Document DocumentBuilder_parse(DocumentBuilder b, String uri) throws SAXException, IOException {
  UnknownHostException lastException = null;
  for (int tries = 0; tries < 2; tries++) {
    try {
      return b.parse(uri);
    } catch (UnknownHostException e) {
      lastException = e;
      System.out.println("Retrying because of: " + e);
      continue;
    }
  }
  throw lastException;
}


来源:https://stackoverflow.com/questions/2906745/networking-code-sometimes-throws-unknownhostexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!