java - 当请求失败时,如何打印显示的状态代码并带有 toast ?

标签 java android httpclient

如果连接失败,需要打印 HttpResponse 响应

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;

需要打印状态代码

最佳答案

检查返回状态。如果它的值不是 200 那么它是失败的并且 toast 它。

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

关于java - 当请求失败时,如何打印显示的状态代码并带有 toast ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34884189/

相关文章:

java - 在JAVA中如何停止程序直到按下按钮?

java - Eclipse 调试器不工作(禁用跳过断点)

java - 今天是一年中的第 n 天

java - 配置 HttpClient 以用作 ReSTLet 客户端

java - 无需 ssl 重新协商的 ssl 客户端身份验证

java - Android 应用程序中的 HttpClient 请求失败,没有任何异常

java - @事务: Is there a way that hibernate can persist child transacttion when parent fails

android - 执行 com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable 时发生故障

Android:显示特殊字符

android - 插件错误 : required plugin "Android Support" is disabled