0

I am making an HTTP request. I want to put a check that if i don't get response within 10 seconds, i would quit the loop. Below is my code. What could be the easiest way to handle this while making an HTTP request. Suggestions welcomed. If you can let me know where exactly i should include those suggestions in my code would be extremely helpful. Thanks

protected String doInBackground(String... params) {
        if (STATUS_STARTED != statusCode) {
            return null;
        }

        final HttpClient client = new DefaultHttpClient();                    


        String email = null;
        String url   = null;

        try {
            email = params[0];
            url   = params[1];

        } catch (ArrayIndexOutOfBoundsException e) {
            Log.e("LOG_TAG", "Invalid parameters are passed to task", e);
            statusCode = STATUS_BADPARAM;
            return null;
        }

        if ( (null == url) || (null == email)) {
            Log.e("LOG_TAG", "One of input params is null: url=" + url + "; email=" + email);
            statusCode = STATUS_BADPARAM;
            return null;
        }

        if(email != null){
            email = email.trim().replaceAll(" ", "");
            //email = email.toLowerCase(); 
            Log.d("EmailLowerCase", "EmailValidator" + email);
        }

        //url += REQUEST_PARAM_START + REQUEST_PARAM_EMAIL + email;
        url += email;

        Log.d("LOG_TAG", "Execute activation request to " + url);

        HttpGet getRequest = null;
        try {
            getRequest = new HttpGet(url);
        } catch (Exception e) {
            Log.e("LOG_TAG", e.getMessage());
        }

        try {
            try {
                int timeoutConnection = 10 * 1000;
                HttpConnectionParams.setConnectionTimeout(client.getParams(), timeoutConnection);
                Log.d("LOG_TAG", "Execute activation request to " + url);
                statusCode = STATUS_IN_PROGRESS;
                HttpResponse response = client.execute(getRequest);
                Log.d("LOG_TAG", "Activation request to " + url
                        + " completed");

                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                case HttpStatus.SC_MULTI_STATUS:
                case HttpStatus.SC_PARTIAL_CONTENT:
                case HttpStatus.SC_RESET_CONTENT:
                case HttpStatus.SC_CREATED:
                case HttpStatus.SC_ACCEPTED:
                case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
                    statusCode = STATUS_COMPLETED;
                    break;
                case HttpStatus.SC_GATEWAY_TIMEOUT:
                    statusCode = STATUS_GATEWAY_TIMEOUT;
                    return "-1";
                default:
                    Log.e("EmailValidator", "Error "
                            + response.getStatusLine().getStatusCode()
                            + " during activation, url=" + url);
                    statusCode = STATUS_ERROR;
                    break;
                }

                String responseStr = null;
                final HttpEntity entityResponse = response.getEntity();
                if (null != entityResponse) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    try {
                        inputStream = entityResponse.getContent();
                        outputStream = new BufferedOutputStream(dataStream,
                                IO_BUFFER_SIZE);
                        copy(inputStream, outputStream);
                        outputStream.flush();
                        responseStr = dataStream.toString();
                        return responseStr;

                    } finally {
                        if (null != inputStream) {
                            inputStream.close();
                        }
                        if (null != outputStream) {
                            outputStream.close();
                        }
                        if (null != dataStream) {
                            dataStream.close();
                        }
                        entityResponse.consumeContent();
                    }
                }
            } 
            catch (ConnectTimeoutException e) {
                getRequest.abort();
                Log.d("ConnectionTimeOut","Connection timout occured");
            } catch (IOException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "I/O error during activation, url=" + url, e);
            } catch (IllegalStateException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Incorrect URL: " + url);
            } catch (Exception e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Error during activation, url=" + url, e);
            }
        } catch (Exception e) {
            Log.e("LOG_TAG", "Error during activation, url=" + url, e);
        } catch (Throwable e) {
            Log.e("LOG_TAG", "Error during activation, url=" + url, e);
        }


        Log.e("LOG_TAG", TRANSMITTING_ERROR);
        return null;
    }
user45678
  • 1,504
  • 6
  • 29
  • 58

2 Answers2

1

try to add HttpConnection Timeout like below

int timeoutConnection = 10 * 1000;
HttpConnectionParams.setConnectionTimeout(client.getParams(),
                timeoutConnection);

EDIT:

You can check if timout will occour inside catch block. see below

 try {
                Log.d("LOG_TAG", "Execute activation request to " + url);
                statusCode = STATUS_IN_PROGRESS;
                HttpResponse response = client.execute(getRequest);
                Log.d("LOG_TAG", "Activation request to " + url
                        + " completed");

                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                case HttpStatus.SC_MULTI_STATUS:
                case HttpStatus.SC_PARTIAL_CONTENT:
                case HttpStatus.SC_RESET_CONTENT:
                case HttpStatus.SC_CREATED:
                case HttpStatus.SC_ACCEPTED:
                case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
                    statusCode = STATUS_COMPLETED;
                    break;
                case HttpStatus.SC_GATEWAY_TIMEOUT:
                    statusCode = STATUS_GATEWAY_TIMEOUT;
                    return "-1";
                default:
                    Log.e("EmailValidator", "Error "
                            + response.getStatusLine().getStatusCode()
                            + " during activation, url=" + url);
                    statusCode = STATUS_ERROR;
                    break;
                }

                String responseStr = null;
                final HttpEntity entityResponse = response.getEntity();
                if (null != entityResponse) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    try {
                        inputStream = entityResponse.getContent();
                        outputStream = new BufferedOutputStream(dataStream,
                                IO_BUFFER_SIZE);
                        copy(inputStream, outputStream);
                        outputStream.flush();
                        responseStr = dataStream.toString();
                        return responseStr;

                    } finally {
                        if (null != inputStream) {
                            inputStream.close();
                        }
                        if (null != outputStream) {
                            outputStream.close();
                        }
                        if (null != dataStream) {
                            dataStream.close();
                        }
                        entityResponse.consumeContent();
                    }
                }
            }catch (ConnectTimeoutException e) {
               Log.i("log","Connection timout occour");
            } catch (IOException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "I/O error during activation, url=" + url, e);
            } catch (IllegalStateException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Incorrect URL: " + url);
            } catch (Exception e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Error during activation, url=" + url, e);
            }
Sonali8890
  • 2,005
  • 12
  • 16
  • Okay and where do i catch its response ? I mean if i want to put toast on timeout then ? How do i do that ? – user45678 Oct 07 '14 at 09:08
  • Hi @Sonali8890 - See my edited question. I did the same as u suggested and i have put 20 seconds delay in my server, after 10 seconds it should have thrown me a Log i have kept inside "ConnectTimeoutException" but nothing came...Am i executing in right way ? – user45678 Oct 07 '14 at 09:25
  • Okay i got it. I also added SocketTimeoutException and it thrown log in that...Anyways somehow i could get a log...he he...Thanks a ton – user45678 Oct 07 '14 at 09:36
0

Refer to this post, it has details about the AsyncTask.get() method, which can be used in this case to wait for a specific amount of time before stop polling the server :-

Android - Setting a Timeout for an AsyncTask?

Community
  • 1
  • 1
divyenduz
  • 2,037
  • 19
  • 38
  • Please don't post an url in this way as no link is generated which we can click. Moreover get() destroys the asynctask function so i would not recomment it. – greenapps Oct 07 '14 at 09:13