gpt4 book ai didi

java - 找不到 URL 内容时更快失败,howto

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:38 30 4
gpt4 key购买 nike

我有一个线程池,它循环遍历一堆页面并检查是否存在某个字符串。如果找到字符串或未找到响应,则几乎是即时的,但是如果服务器离线或应用程序未运行,则获得拒绝似乎需要几秒钟的时间

如何更改代码以更快地失败?

    for (Thread thread : pool) {
thread.start();
}

for (Thread thread : pool) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();

}
}

这是我的运行方法

@Override
public void run() {
for (Box b : boxes) {
try {
connection = new URL(b.getUrl()).openConnection();
scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();

if (content.equals("YES")) {
} else {
System.out.println("\tFAILED ON " + b.getName() + " BAD APPLICATION STATE");
}

} catch (Exception ex) {
System.out.println("\tFAILED ON " + b.getName() + " BAD APPLICATION STATE");
}
}
}

最佳答案

if server is offline or application is not running getting a rejection seems to take seconds

根据您的需要设置超时。

如果您要打开 URLConnectionURL 您可以设置超时。

URL url = new URL(urlPath);
URLConnection con = url.openConnection();
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(readTimeout);
InputStream in = con.getInputStream();

关于java - 找不到 URL 内容时更快失败,howto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431143/

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