Can I set a timeout on a DocumentBuilder?

I am currently reading an XML file with a PHP script (as shown below) that works fine, however now I would like to add some form of HTTP timeout to extract the XML.

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse("http://www.mywebsite.com/returnsXML"); 

Can this be added to my current approach, or do I need to somehow modify the request to support timeouts?

+4
source share
2 answers

You can open the connection manually and set a timeout for URLConnection:

 URL url = new URL("http://www.mywebsite.com/returnsXML"); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); // 10 seconds Document doc = docBuilder.parse(con.getInputStream()); 
+7
source

It seems that there are several compilation questions with a different answer, albeit in spirit.

Here is the version that compiles:

 private static Document fetchDocument(String requestUrl) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); URL url = new URL(requestUrl); URLConnection con = url.openConnection(); con.setConnectTimeout(10000);//The timeout in mills Document doc = db.parse(con.getInputStream()); return doc; } catch (Exception e) { throw new RuntimeException(e); } } 
+1
source

All Articles