在Android中使用EntityUtils会导致线程崩溃

时间:2011-03-13 23:34:37

标签: android

我目前正在尝试将帖子发送到php脚本,这似乎工作正常。但是,当我尝试从HttpEntity中提取字符串时,它会导致线程崩溃。我真的不确定我做错了什么。

HttpClient client = new DefaultHttpClient();
String postURL = "<hidden/not relevant>";
HttpPost categoryPost = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userID", userID));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
categoryPost.setEntity(ent);
responsePOST = client.execute(categoryPost);
HttpEntity resEntity = responsePOST.getEntity();

if (resEntity != null) {
    // TODO Fix this line!!!
    //categoryTest = EntityUtils.toString(resEntity);

    // TODO Then uncomment this line.
    //playedCategories = categoryTest.split(",");

    // This strangely works, but the first use(above) of EntityUtils does not.
    Log.i("RESPONSE", EntityUtils.toString(resEntity));
}

日志将正确的字符串从resEntity输出到LogCat,但它上面的行导致崩溃。

以下错误:
什么时候 categoryTest = EntityUtils.toString(resEntity);
取消注释我在VD屏幕上出现以下错误:“进程*已意外停止”并且LogCat中出现以下错误:

03-13 23:48:13.194: ERROR/AndroidRuntime(220): Uncaught handler: thread Thread-8 exiting due to uncaught exception
03-13 23:48:13.194: ERROR/AndroidRuntime(220): java.lang.IllegalStateException: Content has been consumed
03-13 23:48:13.194: ERROR/AndroidRuntime(220):     at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
03-13 23:48:13.194: ERROR/AndroidRuntime(220):     at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:100)
03-13 23:48:13.194: ERROR/AndroidRuntime(220):     at org.apache.http.util.EntityUtils.toString(EntityUtils.java:112)
03-13 23:48:13.194: ERROR/AndroidRuntime(220):     at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
03-13 23:48:13.194: ERROR/AndroidRuntime(220):     at android.triviarea.data.User.requestAvailableCategories(User.java:112)
03-13 23:48:13.194: ERROR/AndroidRuntime(220):     at android.triviarea.main.MainScreen$1$1.run(MainScreen.java:63)

1 个答案:

答案 0 :(得分:4)

如果您entity is not repeatable,则无法拨打EntityUtils.toString(entity)两次。