Http Connection with timeout does not work

2

Hello, I have a class to read an HTML page, but I wanted it to have a time limit for execution, my code seems to do this, but it does not work as it should, that is, Nothing happening

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

}
    
asked by anonymous 14.07.2014 / 21:04

3 answers

3

Hello Gabriel Good evening,

I took your code and put it to run here and I really could not get it to work. I started searching in some places and found a code that I used in some projects to make the GET request.

Make sure this code helps:

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 questions posted comment! Abs

    
14.07.2014 / 22:13
0

It can also be done this 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: link

    
15.07.2014 / 21:02
0

The problem is that the timeout method of the httpconetion class has nothing implemented. I already had this kind of problem and what I did was create my own timeout. I gave the start on the line before making the request, in case the return arrived before the timeout I canceled my timer. If I did not load my timer I would cancel the request. And then the flow went on like the timeout.

    
16.07.2014 / 18:32