在URL.openStream()Android上设置超时

时间:2013-05-30 15:39:56

标签: android xml url

我在我的应用程序中使用以下内容来连接到URL并解析生成的XML响应。我的麻烦是我无法弄清楚如何在openStream()方法上设置超时,以便它只等待大约5秒,如果没有收到响应,则失败。它只是在等待和等待。有什么想法吗?

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

2 个答案:

答案 0 :(得分: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()));       

答案 1 :(得分:0)

如果您想在网址上进行更改:

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