我有一个在 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 连接。我想这对你也有帮助。
关于java - 如何读取php代码对android java代码的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936047/