Android HTTP帖子中的Chunked Steam错误

时间:2013-05-23 20:00:46

标签: java php android http post

我正在创建一个Android应用程序,它将从存储在Web服务器上的MySQL数据库中提取用户数据。我已经阅读了一些关于HTTP Post的教程,它允许我连接到我工作的数据库。但是,我无法处理从php发送的数据。

我收到的错误是:org.apache.http.MalformedChunkCodingException:Chunked stream意外结束。

这是我写的代码:

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);

} ?&GT;

这样做的最终目标是将来自数据库的JSON响应转换为单独的变量,缓冲的读取器内容只是JSON转换之前的中间步骤。再一次,我只是按照教程,所以如果有人知道不同的方式,我会接受建议。

0 个答案:

没有答案