How to check for POST error

1

I need to check if there was an error in the response from onPostExecute or it gave time out on the server, because sometimes it gives some error in the process and this method does not even start, how could I do such verification?

I call it this:

 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 it runs:

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();
        }
    }
}
}
    
asked by anonymous 04.02.2018 / 15:18

1 answer

2

Considering that your 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();

get() will wait for doInBackground to end, and return onPostExecute .

AsyncTask - final Result

Complementing:

The code is correct, just missing a timeout of HttpURLConnection to not run without forecast 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();
    
22.03.2018 / 10:59