2013-05-30 199 views
5

我在我的應用程序中使用以下內容來連接到URL並解析生成的XML響應。我的麻煩是我找不到一種方法來設置openStream()方法的超時,以便它只等待約5秒,如果沒有收到響應,則失敗。它只是在等待和等待。有什麼想法嗎?在URL.openStream()設置超時Android

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()));   

回答

6

想通了。通過使用URLConnection並調用setConnectionTimeout和setReadTimeout方法,我能夠實現我想要的。更新後的代碼如下....

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()));  
0

,如果你想改變它的網址:

website.openConnection().setReadTimeout(5000); 
website.openConnection().setConnectTimeout(5000);