Networking code sometimes throws UnknownHostException

前端 未结 4 836
迷失自我
迷失自我 2020-11-29 13:30

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?

相关标签:
4条回答
  • 2020-11-29 13:50

    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.

    0 讨论(0)
  • 2020-11-29 13:51

    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.

    0 讨论(0)
  • 2020-11-29 13:53

    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.

    0 讨论(0)
  • 2020-11-29 14:04

    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 讨论(0)
提交回复
热议问题