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

[英]Set timeout on URL.openStream() Android


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并解析生成的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 个解决方案

#1


6  

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并调用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()));       

#2


0  

if you want to change it on the URL:

如果你想在URL上更改它:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/05/30/bbd9e2176219645e76291f2b6ada6de5.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号