有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何读取php代码对安卓 java代码的响应

我有一个在wamp服务器上运行的php代码,它以JSON数组的形式返回数据库的所有内容。我想将我的安卓应用程序连接到此php文件。如何获得这个php文件对我的安卓 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);
?>

以下是我目前在安卓代码中所做的事情(但我所做的大部分被认为是不推荐的):

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) 个答案