2011-01-18 13 views
30

Me golpearon debido a IllegalStateException en el siguiente código. ¿Alguien puede ayudarme? Código: mensajeIllegalStateException: el contenido se ha consumido

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.ParseException; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.protocol.HTTP; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.os.Bundle; 
import android.telephony.gsm.GsmCellLocation; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class Login extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.login); 
     Button bt = (Button) findViewById(R.id.logbt); 
     final EditText user = (EditText) findViewById(R.id.loguser); 
     final EditText pw = (EditText) findViewById(R.id.logpw); 
     bt.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (user.getText().toString() != "" && pw.getText().toString() != "") { 
        Thread t = new Thread() { 
         public void run() { 
          try { 
           HttpClient client = new DefaultHttpClient(); 
           String postURL = "http://surfkid.redio.de/login"; 
           HttpPost post = new HttpPost(postURL); 
           ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
           params.add(new BasicNameValuePair("username", user.getText().toString())); 
           params.add(new BasicNameValuePair("password", md5(pw.getText().toString()))); 
           UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8); 
           post.setEntity(ent); 
           HttpResponse responsePOST = client.execute(post); 
           HttpEntity resEntity = responsePOST.getEntity(); 
           final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity)); 
           Log.e("XXX", EntityUtils.toString(resEntity)); 
          } catch (Exception e) { 
           Log.e("XXX", e.toString()); 
          } 
         } 
        }; 
        t.start(); 
        // Log.e("XXX",s); 
       } 
      } 
     }); 
    } 

    private String md5(String in) { 
     MessageDigest digest; 
     try { 
      digest = MessageDigest.getInstance("MD5"); 
      digest.reset(); 
      digest.update(in.getBytes()); 
      byte[] a = digest.digest(); 
      int len = a.length; 
      StringBuilder sb = new StringBuilder(len << 1); 
      for (int i = 0; i < len; i++) { 
       sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16)); 
       sb.append(Character.forDigit(a[i] & 0x0f, 16)); 
      } 
      return sb.toString(); 
     } catch (NoSuchAlgorithmException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

Logcat:

01-18 18: 39: 53.383: ERROR/XXX (7113): java.lang.IllegalStateException: contenido se ha consumido

+2

¿Qué "no funciona" al respecto? – Falmarri

+0

¿Vio Logcat junto a la ventana de la consola, si no puede ver eso, haga clic en el Menú de Windows, luego haga clic en otros y Chosse Logcat, y díganos si tuvo problemas para mostrar logcat o no, por favor sea rápido –

+0

en el registrador no hay registro con XXX aparece – user547995

Respuesta

105

Usted puede consumir Content única a la vez de una Entity

en la línea:

final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity)); 

que han consumido el contenido y otra vez que está utilizando la misma al aquí:

Log.e("XXX",EntityUtils.toString(resEntity)); 

Que por qué está causando IllegalStateException: Content has been consumed

Así que la solución está aquí:

String _response=EntityUtils.toString(resEntity); // content will be consume only once 
final JSONObject jObject=new JSONObject(_response); 
Log.e("XXX",_response); 
+29

Ugh, a veces (está bien muchas veces) java está tan retrasado. – Timmmm

+0

Impresionante, impresionante. –

+0

Dios mío, me salvaste la vida :) –

3

En primer lugar, esto tiene que ser un error que cada programador de Android nuevo hace y se pregunta aquí todos los días. Tiene

user.getText().toString()!= ""&& pw.getText().toString()!= "" 

Esto no hace lo que quiere. Necesita

!user.getText().toString().equals("")&& !pw.getText().toString().equals("") 

Además, debe imprimir stacktrace. En su excepción, necesita

e.printStackTrace() 

en lugar de entrar

e.toString() 
+0

gracias por su ayuda ... pero esta no es la solución para resolver mi problema – user547995

+0

Por cierto, en este tema fuera del tema, prefiero 'Log.e (TAG," Error ", excepción)' sobre 'excepción .toString() '. – EboMike

+0

podría alguien compilar esa clase (usuario: prueba pw: sers) – user547995

1

Acabo de tratar con un caso de un cheque nulo en la entidad causando que se marque como "consumido". Espero que mi dolor de cabeza ayude a alguien más allá. La respuesta de

Vikas Patidar ayudó a averiguar la clave del enigma, por lo que muchas gracias

5

también es sucede si está escribiendo la declaración consume en las expresiones de la depurador !!!
(por ejemplo, si está haciendo "ver" algo así como EntityUtils.toString(resEntity))

Cuestiones relacionadas