How to read response of php code to android java code

梦想的初衷 提交于 2020-01-25 12:52:47

问题


I have a php code running on a wamp server which returns all the contents of database as a JSON array. I want to connect my android app to this php file. How do i get the response of this php file to my android java code.

MY PHP CODE:

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

Also here is what I'm currently doing in my android code (But most of what i am doing is deemed deprecated):

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:


I also connect php web services(Json formatted) with android according to this tutorial. I think it will also helpful to you also.

How to connect Android with PHP, MySQL



来源:https://stackoverflow.com/questions/31936047/how-to-read-response-of-php-code-to-android-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!