33

I got struck because of IllegalStateException in the following code. Can anybody please help me? Code:

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 message:

01-18 18:39:53.383: ERROR/XXX(7113): java.lang.IllegalStateException: Content has been consumed

Smi
  • 13,850
  • 9
  • 56
  • 64
user547995
  • 2,036
  • 8
  • 33
  • 62

4 Answers4

107

You can consume Content only at once from an Entity

in the line :

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

you have consumed content and again you are using the same at here:

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

That why it is causing IllegalStateException: Content has been consumed

So the solution is here:

String _response=EntityUtils.toString(resEntity); // content will be consume only once
final JSONObject jObject=new JSONObject(_response);
Log.e("XXX",_response);
Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
  • Thank you so much.. This is really useful info.. Consuming of content after httptresponse can be done only once.. i was also doing the same mistake, but now got it perfectly. Thanks a lot. – Anil Chahal Jul 23 '14 at 06:20
7

it's also happens if you are writing the consuming statement in the Expressions of the debugger!!!
(e.g if you are doing "watch" to something like EntityUtils.toString(resEntity))

dvrm
  • 3,749
  • 4
  • 34
  • 43
3

First, this has to be a mistake that every single new android programmer makes and it's asked here every single day. You have

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

This doesn't do what you want it to. You need

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

Also, you need to print the stacktrace. In your exception, you need

e.printStackTrace()

instead of logging

e.toString()
Falmarri
  • 47,727
  • 41
  • 151
  • 191
1

I just dealt with a case of a null check on the entity causing it to be flagged as "consumed". Hope my headache will help someone else out there.

Vikas Patidar's answer helped me figure out the key to the riddle, so many thanks

Joe Plante
  • 6,308
  • 2
  • 30
  • 23