0

Hello I have never worked with HttpResponses before and I want to be able to disconnect from the network after 3 minutes given that the user loses connection from the network. Is there a full code wherein I can see such thing?

2 Answers2

0

I know two possible approaches:

  1. The simplest way, using DefaultHttpClient, already explained in isma3l recommended link:

Something like this:

private DefaultHttpClient httpClient;
// set connection timeout to 1 second
HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
// set socket timeout to 1 second
HttpConnectionParams.setSoTimeout(httpParameters, 1000);
httpClient = new DefaultHttpClient(httpParameters);
/* === and then, use your httpClient to perform your operations... === */
  1. The hardcore way: manually handle the connection with thread/handler by calling the Http operations in another thread with a handler to receive its callbacks. In the handler, you call a postDelayed method passing as parameter a Runnable to take care of the timeout.

Something like this:

// create a handler to load content
private final Runnable loadContent = new Runnable() {
    @Override
    public void run() {
        /* === CALL HTTP AND PROCESS IT HERE === */
        // remove the timeout runnable after receiving http response
        handler.removeCallbacks(timeoutRunnable);
    }
}
// create a handler to handle timeout
private final Runnable timeoutRunnable = new Runnable() {
    @Override
    public void run() {
        handler.sendEmptyMessage(1);
    }
};
// create a handler to handle the connection
private final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1: // timeout
                handler.removeCallbacks(timeoutRunnable);
                break;
            /* === OTHER MESSAGES TO HANDLE OTHER SITUATIONS === */
        }
    }
};
// call the connection inside a new thread
private void createNewLoader() {
    // create a delayed runnable with a timeout of 1 second
    handler.postDelayed(timeoutRunnable, 1000);
    // call the content loader
    new Thread(loadContent).start();
}

Hope it helps.

Community
  • 1
  • 1
Marcelo
  • 2,075
  • 5
  • 21
  • 38
0

Don't use DefaultHttpClient, Google deprecated it, stopped supporting it, and recommends using URLConnection which is faster. Timeouts are handled as so:

// Prepare connection
URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(TIMEOUT);
conn.setReadTimeout(TIMEOUT);
Cigogne Eveillée
  • 2,178
  • 22
  • 36