How to check if there was an error in the POST

Asked

Viewed 73 times

1

I need to check if there was any error in the reply of onPostExecute or gave time out on the server, because sometimes it gives some error in the process and this method does not even start, as I could do such check?

I call him that:

 ConnectivityManager connMgr = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                url = "https://...";

                parametros = "paramentro=" + string;

                new minhaclasse.SolicitaDados().execute(url);

            } else {
                Toast.makeText(getApplicationContext(), "Erro, tente novamente!", Toast.LENGTH_LONG).show();
            }

And then he executes:

private class SolicitaDados extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        return Conexao.postDados(urls[0], parametros);
    }

    @Override
    protected void onPostExecute(String resultado) {

        if(resultado != null && resultado != "") {

        }
    }
}

Connection class:

  public class Conexao {

  public static String postDados(String urlUsuario, String parametrosUsuario) {
    URL url;
    HttpURLConnection connection = null;

    try {

        url = new URL(urlUsuario);
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        connection.setRequestProperty("Content-Lenght", "" + Integer.toString(parametrosUsuario.getBytes().length));

        connection.setRequestProperty("Content-Language", "pt-BR");

        //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        OutputStreamWriter outPutStream = new 
        OutputStreamWriter(connection.getOutputStream(), "utf-8");
        outPutStream.write(parametrosUsuario);
        outPutStream.flush();
        outPutStream.close();

        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

        String linha;
        StringBuffer resposta = new StringBuffer();

        while((linha = bufferedReader.readLine()) != null) {
         resposta.append(linha);
            resposta.append('\r');
        }

        bufferedReader.close();

        return resposta.toString();

    } catch (Exception erro) {

        return  null;
    } finally {

        if(connection != null) {
            connection.disconnect();
        }
    }
}
}
  • If you put the 'doInBackground' code snippet inside a Try-catch block would resolve? I didn’t run the tests.

1 answer

2


whereas his AsyncTask is returning a value:

// Instancia o obj
SolicitaDados obj = new SolicitaDados();
// Executa a classe `AssyncTask`
obj.execute();
// Puxa o retorno (se for int)
int retorno = obj.get();

The get() will wait for the end of the doInBackground, and return your onPostExecute.

Asynctask - final Result

Complementing:

The code is correct, only remaining to treat a timeout HttpURLConnection not to run without prediction for whatever reason.

Example:

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
httpURLConnection.setRequestMethod("POST"); 
httpURLConnection.setReadTimeout(3000); 
httpURLConnection.setConnectTimeout(3000); 
httpURLConnection.setDoInput(true); 
httpURLConnection.setDoOutput(true); 
httpURLConnection.connect();
  • Hello, good morning friend, I did not understand very well the functioning of this code snippet, can explain me better?

  • I changed the answer. But if you want more complete, post your full class, working, if not, we have no way to exemplify on top of your code.

  • Ah, now I understand, but I already received the return in the String result of onPostExecute, I would like to know how to verify if gave time out, for example during the process

  • @Wotonsampaio there depends on your structure as you are requesting. I will post an example with the httpURLConnection

  • Look, I’ll post the connection class, just a moment

  • The way I’m doing, before doing the post it checks if there is internet, but if the person is connected in a network that does not have internet, he will spend the rest of his life doing the process, not crasha, just keep loading infinitely

  • The connection test, it would be better to do before calling the method. If it has connection, calls, if not, does not call.

  • Take a look now, I saw how I’m testing the connection and the class

Show 4 more comments

Browser other questions tagged

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