Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set timeout on URL.openStream() Android

Tags:

android

url

xml

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()));        
like image 335
Phil Avatar asked May 30 '13 15:05

Phil


1 Answers

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()));       
like image 143
Phil Avatar answered Oct 11 '22 16:10

Phil