开发者

Possible to set a timeout on a DocumentBuilder?

I am currently reading an XML file from a PHP script (as below) which works fine, however I'd now like to add some form of HTTP timeout to retrieving the XML.

DocumentBuilderFactory docBuilderFa开发者_如何学编程ctory = DocumentBuilderFactory.newInstance();  
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse("http://www.mywebsite.com/returnsXML");

Can this easily be added given my current approach, or would I need to change the request somehow to support timeouts?


You can open connection manually and set 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());


There seems to be a few compile issues with the other answer, though correct in spirit.

Here is a 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);
        }
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜