Http Connection with timeout does not work

Asked

Viewed 489 times

2

Hello I’m with a class to make to read an HTML page, but I wanted it to have a time limit for the execution, my code seems to do it, but it does not work as it should, IE, the time I put is not happening anything

private class GrabURL extends AsyncTask<String, Void, Void> {
    InputStream is = null;
    int response = -1;
    URL url;
    URLConnection conn;
    String retorno = null;
    private ProgressDialog Dialog = new ProgressDialog(TelaLogin.this);


    protected void onPreExecute() {
        Dialog.setMessage("Carregando. Aguarde...");
        Dialog.setCanceledOnTouchOutside(false);
        Dialog.show();
    }
     protected Void doInBackground(String... urls) {
        try {               
            url = new URL(urls[0]);
            conn = url.openConnection();
            if(!(conn instanceof HttpURLConnection))
            {
                retorno = "Erro-Tempo";
                return null;
            }
            else
            {
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.setReadTimeout(8000); // 8 segundos para ler
                httpConn.setConnectTimeout(4000); // 4 segundos para conectar
                httpConn.connect();
                response = httpConn.getResponseCode();
                if(response == HttpURLConnection.HTTP_OK)
                {
                    is = httpConn.getInputStream();
                    retorno = inputStreamToString(is).toString();
                }
                else
                    retorno = "Erro-Tempo";
            }
        }catch(SocketTimeoutException ex){
            retorno = "Erro-Tempo";
            cancel(true);
        }catch (ClientProtocolException e) {
            retorno = "Invalido-Erro";
            cancel(true);
        } catch (IOException e) {
            retorno = "Invalido-Erro";
            cancel(true);
        }
        return null;
    }

    protected void onPostExecute(Void unused) {
        Dialog.dismiss();
        trataRetorno(retorno);     
    }

}
  • What is going wrong, what is your claim to the timeout’s? What’s wrong? What’s the problem?

  • I want to take too long to download the content to be canceled and generate a message to the user saying that his connection is bad. My code keeps trying to connect all the time, even if it takes more than 8 seconds, it does not cancel any time.

  • Vixi, it seems to me to be a problem that, look at this another topic in English, you’re running this on a AsyncTask?

  • I am running the way it is up there "new Graburl(). execute("...");" .

3 answers

3


Hello Gabriel Good afternoon,

I got your code put in here to run and I really couldn’t get it to work. I started looking in some places and found a code I used in some projects to make the GET request.

Make sure that code helps you:

private class GrabURL extends AsyncTask<String, Void, String> {
        private ProgressDialog Dialog = new ProgressDialog(TelaLogin.this);

        @Override
        protected void onPreExecute() {
            Dialog.setMessage("Carregando. Aguarde...");
            Dialog.setCanceledOnTouchOutside(false);
            Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
            String retorno = null;

            try {               
                HttpParams httpParameters = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParameters, 4000);
                HttpConnectionParams.setSoTimeout(httpParameters, 4000);
                HttpClient client = new DefaultHttpClient(httpParameters);

                HttpGet getRequest = new HttpGet(urls[0]);
                HttpResponse httpResponse = client.execute(getRequest);

                HttpEntity entity = httpResponse.getEntity();

                if (entity != null) {
                    InputStream instream = entity.getContent();
                    retorno = convertStreamToString(instream);

                    instream.close();
                }
            } catch (ClientProtocolException ex) {
                Log.e("TAG", ex.getMessage(), ex);
                cancel(true);
            } catch (IOException ex) {
                Log.e("TAG", ex.getMessage(), ex);
                cancel(true);
            }

            return retorno;
        }

        @Override
        protected void onPostExecute(String retorno) {
            super.onPostExecute(retorno);

            Dialog.dismiss();
            //trataRetorno(retorno);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();

            Dialog.dismiss();
        }
    }

Any doubt put comment! Abs

0

It can also be done that way:

//Recupera um content via HTTP GET.
public static InputStream getInputStreamFromUrl(String url) {
  InputStream content = null;
  try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));
    content = response.getEntity().getContent();
  } catch (Exception e) {
    Log.("[GET REQUEST]", "Network exception", e);
  }
    return content;
}

Reference: http://www.androidsnippets.com/executing-a-http-get-request-with-httpclient

0

The problem is that the timeout method of the httpconetion class has nothing implemented. I’ve had this kind of problem before and what I did was create my own timeout. I would start the line before making the request, in case the return arrived before the timeout I would cancel my timer. If I did not load my timer I would cancel the request. And then the flow would go as if it were the timeout.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.