开发者

Networking code sometimes throws UnknownHostException

I am trying to data from a server. S开发者_如何学编程ometimes my code fails due to an UnknownHostException. Why is that? What is the cause of this problem?


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.


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.


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜