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

标签 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;

    }
}

最佳答案

我还根据本教程将 php web 服务(Json 格式)与 android 连接。我想这对你也有帮助。

How to connect Android with PHP, MySQL

关于java - 如何读取php代码对android java代码的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936047/

相关文章:

java - android.content.res.Resources$NotFoundException : String resource ID #0x1

资源 getString 的 Android IndexOutOfBound 异常

java - android-哪个线程在SensorChanged上运行?

java - 获取android手机的设备配置

java - 尝试有意共享 mp3,但不包含文件扩展名

java - 初始化后 JPanel 的 setSize

php - 谷歌应用引擎 "Error parsing ./app.yaml: Unknown url handler type"

php - 删除行 PHP

PHP exec 等待返回键

java - 如何从字符串数组列表中随机选择