Networking code sometimes throws UnknownHostException

前端 未结 4 861
迷失自我
迷失自我 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 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;
    }
    

提交回复
热议问题