我正在尝试从网页中获取数据,但是如果该页面不可用,程序将运行很长时间直到超时。我需要它来尝试获取网页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