如何阅读php代码对android java代码的响应

时间:2015-08-11 07:48:04

标签: java php android httpresponse

我在wamp服务器上运行了一个php代码,它将数据库的所有内容作为JSON数组返回。我想将我的Android应用程序连接到这个php文件。我怎么得到这个PHP文件的响应到我的android java代码。

我的PHP代码:

<?php

$con = mysqli_connect("localhost","root","2015","testdatabase") or die("Error " . mysqli_error($link));
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$result = mysqli_query($con,"SELECT * FROM Customer");
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysqli_close($con);
?>

这也是我目前在我的Android代码中所做的事情(但我正在做的大部分内容都被视为已弃用):

public JSONArray GetAllCustomers()
    {
        // URL for getting all customers
        String url = "http://127.0.0.1/Customers/getAllCustomers.php";

        // Get HttpResponse Object from url.
        // Get HttpEntity from Http Response Object
        HttpEntity httpEntity = null;

        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);

            httpEntity = httpResponse.getEntity();

        } catch (ClientProtocolException e) {
            // Signals error in http protocol
            e.printStackTrace();

            //Log Errors Here

        } catch (IOException e) {
            e.printStackTrace();
        }

        // Convert HttpEntity into JSON Array
        JSONArray jsonArray = null;

        if (httpEntity != null) {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);

                Log.e("Entity Response  : ", entityResponse);

                jsonArray = new JSONArray(entityResponse);

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return jsonArray;

    }
}

1 个答案:

答案 0 :(得分:1)

我也根据本教程将php web服务(Json格式化)与android连接。我认为它对你也有帮助。

How to connect Android with PHP, MySQL