当请求失败时,如何用toast打印显示状态代码?

时间:2016-01-19 18:20:16

标签: java android httpclient

如果conexion失败,需要打印HttpResponse response

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    private ProgressDialog pDialog;

    @Override
    protected String doInBackground(String... params) {

        return GET();

    }

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Iniciando sesión...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override

    protected void onPostExecute(String result) {

        pDialog.dismiss();

}




public String GET() {

        String url = "http://"+ippref+":8080/Activo/webresources/activo.entities.coreusuario/usuarios/" + usuario_ws + "/" +contrasenia_ws+ "";
        String result = "";
        BufferedReader inStream = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpRequest = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpRequest);

            response.getStatusLine().getStatusCode();
            inStream = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent()));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = inStream.readLine()) != null) {
                buffer.append(line);
            }
            inStream.close();
            result = buffer.toString();

            respuesta_ws = Integer.valueOf(result);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;

需要打印状态码

2 个答案:

答案 0 :(得分:1)

使用此:

Toast.makeText(getApplicationContext(),
                    response.getStatusLine().getStatusCode(),
                        Toast.LENGTH_LONG).show();

导入android.widget.Toast

您可以通过更改Toast.LENGTH_LONG

来更改吐司的时间

当然如果你只想在http响应错误时显示toast,那么添加逻辑来检查错误情况并在那里做吐司。 希望这可以帮助。 :)

答案 1 :(得分:1)

检查退货状态。如果它的值不是200,那么它就会失败并为它干杯。

if(response.getStatusLine().getStatusCode()!=200){
  Toast.makeText(getApplicationContext(),
                "Request failure!",
                    Toast.LENGTH_LONG).show();
}