Java URLConnection超时 [英] Java URLConnection Timeout
本文介绍了Java URLConnection超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从HTTP URL解析XML文件。如果XML提取时间超过这个,我想配置15秒的超时,我想报告超时。出于某种原因,setConnectTimeout和setReadTimeout不起作用。以下是代码:
I am trying to parse an XML file from an HTTP URL. I want to configure a timeout of 15 seconds if the XML fetch takes longer than that, I want to report a timeout. For some reason, the setConnectTimeout and setReadTimeout do not work. Here's the code:
URL url = new URL("http://www.myurl.com/sample.xml");
URLConnection urlConn = url.openConnection();
urlConn.setConnectTimeout(15000);
urlConn.setReadTimeout(15000);
urlConn.setAllowUserInteraction(false);
urlConn.setDoOutput(true);
InputStream inStream = urlConn.getInputStream();
InputSource input = new InputSource(inStream);
我正在捕捉SocketTimeoutException。
And I am catching the SocketTimeoutException.
谢谢
Chris
Thanks Chris
推荐答案
试试这个:
import java.net.HttpURLConnection;
URL url = new URL("http://www.myurl.com/sample.xml");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(15 * 1000);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
或
OR
import org.jsoup.nodes.Document;
Document doc = null;
try {
doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
} catch (Exception e) {
//log error
}
了解如何使用Jsoup: http://jsoup.org / cookbook / input / load-document-from-url
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
这篇关于Java URLConnection超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文