user1462299
user1462299

Reputation: 4287

HttpUrlConnection setConnectTimeout doesn't work?

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.

Upvotes: 5

Views: 9278

Answers (1)

Zaz Gmy
Zaz Gmy

Reputation: 4356

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

Upvotes: 8

Related Questions