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