I am using the following in my app to connect to a URL and parse the resulting XML response. My trouble is I can not figure out a way to set a timeout on the openStream() method so that it only waits about 5 seconds and if no response is received, fails. It just keeps waiting and waiting. Any thoughts?
URL website = new URL(sb.toString());
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
DataHandler h = new DataHandler();
xr.setContentHandler(h);
xr.parse(new InputSource(website.openStream()));
Figured it out. By using URLConnection and calling the setConnectionTimeout and setReadTimeout methods I am able to achieve what I want. Updated code below....
URLConnection conn = new URL(sb.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
DataHandler h = new DataHandler();
xr.setContentHandler(h);
xr.parse(new InputSource(conn.getInputStream()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With