gpt4 book ai didi

Java URL连接超时

转载 作者:IT老高 更新时间:2023-10-28 20:29:17 24 4
gpt4 key购买 nike

我正在尝试从 HTTP URL 解析 XML 文件。我想配置 15 秒的超时,如果 XML 提取时间比这更长,我想报告超时。由于某种原因,setConnectTimeout 和 setReadTimeout 不起作用。代码如下:

          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。

谢谢克里斯

最佳答案

试试这个:

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

       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

关于Java URL连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3163693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com