我一直试图让我的Android应用程序将数据发布到PHP文件,然后将该数据写入数据库,但是我遇到了一些麻烦。
我收到了这个错误,但不是强制关闭或任何事情。
Logcat输出:
08-13 20:29:42.859: I/postData(11950): HTTP/1.1 200 OK
08-13 20:29:42.859: E/log_tag(11950): Error in http connectionjava.lang.IllegalStateException: Content has been consumed
这是有问题的代码,它正在做我所有的HTTP POST事情,即机器方面的事情:
SubmitWord task = new SubmitWord();
task.execute(new String[] { "http://www.hanged.comli.com/main.php" });
上面的代码调用了这个异步任务:
private class SubmitWord extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",myId));
nameValuePairs.add(new BasicNameValuePair("rival",newname));
nameValuePairs.add(new BasicNameValuePair("word","HELLOHOMO"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
InputStream is = entity.getContent();
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
@Override
protected void onPostExecute(String result)
{
mText.setText("DONE");
}
}
这是PHP方面的事情:
<?php
/// REMOVED DATABASE DETAILS
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
mysql_query("INSERT INTO currentgames (victim, rival, wordguess, won) VALUES('$victim', '$rival', '$word', '$won'))");
我很确定这只是Java / Android部分我错了,但我无法弄清楚我的生活中我做错了什么,我尝试了各种不同的POSTING数据方法并阅读了许多关于使用HTTPOST的教程。也许我只是没有正确理解。
答案 0 :(得分:2)
罪魁祸首是你打电话给getContent();
两次。
根据javadoc
返回实体的内容流。期望可重复实体为此方法的每次调用创建一个新的InputStream实例,因此可以多次使用。不可重复的实体应返回相同的InputStream实例,因此不能多次使用。