0

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

}
4

2 回答 2

2

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

urlConnection.setConnectTimeout(10000); // 10000 milliseconds
于 2013-05-02T09:02:27.407 回答
1

您可能应该使用可以大大简化这些事情的 HTTP 库(如Apache 的 HTTPClient )。如果您使用的是 HTTPClient,您将执行以下操作:

            // Set the timeout to 20-seconds.
            final HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
            HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

            DefaultHttpClient httpClient = new DefaultHttpClient(cm, httpParams);
            HttpPost postRequest = new HttpPost(URL);
            HttpResponse response;
            response = httpClient.execute(postRequest);
于 2013-05-02T08:58:24.380 回答