>我有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 db.我也导入了SendAPI.PHP(您可以忽略)这只是我发送数据的类.基本上它包含了我想要使用的一些查询.比如sendaccelerationData().基本上类与存储过程类似.
以上是内存溢出为你收集整理的php – 通过JSON将数据从android发送到服务器全部内容,希望文章能够帮你解决php – 通过JSON将数据从android发送到服务器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)