通过JSON将数据从Android发送到服务器
- 我有MySQL数据库服务器
- 我需要通过JSON更新和检索MySQL服务器中的数据
所以,我想知道如何做到这一点,并且让这个示例语句感到困惑:
HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");
这意味着我需要先编写与PHP服务器连接的应用程序代码,然后再编写php以连接数据库。
回答:
要将数据发送到服务器,您可以执行以下操作:
private void sendData(ArrayList<NameValuePair> data){
// 1) Connect via HTTP. 2) Encode data. 3) Send data.
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.blah.com/AddAccelerationData.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
然后发送让说:
private void sendAccelerationData(String userIDArg, String dateArg, String timeArg, String timeStamp, String accelX, String accelY, String accelZ)
{
fileName = "AddAccelerationData.php";
//Add data to be send.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
nameValuePairs.add(new BasicNameValuePair("userID", userIDArg));
nameValuePairs.add(new BasicNameValuePair("date",dateArg));
nameValuePairs.add(new BasicNameValuePair("time",timeArg));
nameValuePairs.add(new BasicNameValuePair("timeStamp",timeStamp));
nameValuePairs.add(new BasicNameValuePair("accelX",accelX));
nameValuePairs.add(new BasicNameValuePair("accelY",accelY));
nameValuePairs.add(new BasicNameValuePair("accelZ",accelZ));
this.sendData(nameValuePairs);
}
因此服务器上的AddAccelerationData.php文件为:
<?php/*
* What this file does is it:
* 1) Creates connection to database.
* 2) Retrieve the data being send.
* 3) Add the retrieved data to database 'Data'.
* 4) Close database connection.
*/
require_once '../Connection.php'; //connect to a database/disconnect handler.
require_once '../SendAPI.php'; //deals with sending querys.
$server = new Connection();
$send = new Send();
//Connect to database.
$server->connectDB();
//Retrieve the data.
$userID = $_POST['userID'];
$date = $_POST['date'];
$time = $_POST['time'];
$accelX = $_POST['accelX'];
$accelY = $_POST['accelY'];
$accelZ = $_POST['accelZ'];
//Add data to database 'Data'. //Personal method to query and add to database.
$send->sendAccelerationData($userID, $date, $time, $timeStamp, $accelX, $accelY, $accelZ);
//Disconnect from database.
$server->disconnectDB();
?>
这是我最近使用的示例。只是在php文件中要注意。我导入Connection.php,这只是处理与数据库的连接。因此,只需将其替换为用于连接到MySQL数据库的代码即可。我也导入了SendAPI.php(您可以忽略),这只是我发送数据的类。基本上,它包含一些我想使用的查询。如sendAccelerationData()。基本上,类与存储过程的类相似。
以上是 通过JSON将数据从Android发送到服务器 的全部内容, 来源链接: utcz.com/qa/421207.html