gpt4 book ai didi

Java获取网页源或者超时

转载 作者:行者123 更新时间:2023-12-01 23:50:38 24 4
gpt4 key购买 nike

我正在尝试从网页获取数据,但如果该页面不可用,程序将运行很长时间直到超时。我需要它尝试获取网页 10 秒,如果在这段时间内没有得到响应,则返回 null。请问我怎样才能让它这样工作?

这是我获取数据的方式:

public int getThreadData( String address ) throws IOException{
String valueString = null;
URL url = new URL( "http://" + address + ":8080/web-console/ServerInfo.jsp" );
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty( "User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3)
Gecko/20100401" );
BufferedReader br = new BufferedReader( new InputStreamReader
( urlConnection.getInputStream(), "UTF-8" ) );

String inputLine;

while ( ( inputLine = br.readLine() ) != null )
{
if ( inputLine.contains( "#Threads" ) )
{
valueString = inputLine.substring( inputLine.indexOf( "/b>" ) + 3 );
valueString = valueString.substring( 0, valueString.indexOf( "<" ) );
}
}
br.close();

return Integer.parseInt( valueString );

}

最佳答案

您是否尝试过如下设置连接超时:

urlConnection.setConnectTimeout(10000); // 10000 milliseconds

关于Java获取网页源或者超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16333919/

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