我试图像这样使用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)”块。怎么了

P.S.为了进行测试,我制作了一个页面,该页面使服务器进入休眠状态达10秒钟。

最佳答案

试试这个:

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();
}

关于android - HttpUrlConnection setConnectTimeout不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11392601/

10-11 15:26