5

我正在尝试像这样使用 setConnectTimeout 函数:

protected HttpURLConnection getConnection() throws SocketTimeoutException, IOException{
    Log.d("HTTPRequest", address);
    URL page = new URL(address);
    HttpURLConnection connection = (HttpURLConnection) page.openConnection();

    connection.setUseCaches(cacheResult);
    connection.setConnectTimeout(3000);
    connection.connect();
    return connection;
}

进而:

public String getTextData() throws InternetConnectionUnavailableException {
    try{
        HttpURLConnection conn = getConnection();
        StringBuffer text = new StringBuffer();
        InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line;

        while (true) {
            if((line = buff.readLine()) != null){
                text.append(line);
            }else{
                break;
            }
        }
        return (text.toString());
    } catch (SocketTimeoutException socketTimeoutException) {
            throw new InternetConnectionUnavailableException();
    } catch (IOException ioException) {
            throw new InternetConnectionUnavailableException();
    }
}

但是,它永远不会进入“catch (SocketTimeoutException socketTimeoutException)”块。这里有什么问题。

PS 对于测试,我制作了一个页面,让我的服务器进入睡眠状态 10 秒。

4

1 回答 1

8

试试这个:

try {

   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds
   con.setReadTimeout(socketTimeout);
   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   e.printStackTrace();
} catch (java.io.IOException e) {
    e.printStackTrace();
}
于 2012-07-09T09:59:20.673 回答