我正在创建一个 android 应用程序,该应用程序将从存储在 Web 服务器上的 MySQL 数据库中提取用户数据。我已经阅读了一些关于 HTTP Post 的教程,这些教程允许我连接到我开始工作的数据库。但是,我无法处理从 php.ini 发送的数据。
我收到的错误是:org.apache.http.MalformedChunkCodingException:分块流意外结束。
这是我写的代码:
String name = username.getText().toString(); //username is a TextView field
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("user",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(location);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error in http connection"+e.toString());
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("log_tag", result);
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", e.toString());
}
该错误似乎出现在对字符串的转换响应部分中。我已经查找了几个关于我收到的类似错误的问题,但我读到的似乎没有多大帮助,或者我只是对 http 客户端编码知之甚少......可能是后者。任何帮助将不胜感激,谢谢!
这里也是PHP:
<?php
$con = mysqli_connect("/**connection*/");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM userNames WHERE user='".$_POST['name']."')";
if ($result == NULL)
{
die();
}
else
{
//TODO:get row to java
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
mysql_close();
}
mysqli_close($con);
} ?>
这样做的最终目标是将来自数据库的 JSON 响应转换为单独的变量,缓冲的阅读器只是 JSON 转换之前的中间步骤。同样,我只是按照教程进行操作,所以如果有人知道不同的解决方法,我愿意接受建议。