当请求失败时,我如何打印显示的状态码?

How i can println the statuscode in display with a toast when the request is fail?

连接失败需要打印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;

需要打印状态码

使用这个:

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

进口android.widget.Toast

你可以通过改变Toast.LENGTH_LONG

来改变吐司的时间

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

检查 return 状态。如果它的值不是 200 那么它是一个失败并祝酒它。

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