Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpUrlConnection setConnectTimeout doesn't work?

Tags:

android

I'm trying to get use of setConnectTimeout function like this:

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

and then:

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

However, it never gets in the "catch (SocketTimeoutException socketTimeoutException)" block. What's wrong here.

P.S. For the testing I've made a page that puts my server into sleep for 10 seconds.

like image 584
user1462299 Avatar asked Jul 09 '12 09:07

user1462299


1 Answers

try this:

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();
}
like image 121
Zaz Gmy Avatar answered Oct 27 '22 20:10

Zaz Gmy