将数据从android发送到网站并在网上接收

时间:2011-08-04 10:32:34

标签: android http web network-programming client-server

我是Android开发的新手, 我想开发一个Android应用程序,它将数据发送到我的网站,(例如经度和纬度),我的问题是如何从android发送数据以及如何在网站上获取/捕获它。

1 个答案:

答案 0 :(得分:1)

这可能会有所帮助。我刚才做的一个例子就是将加速数据发送到服务器,这样我就可以将数据存储到mysql数据库中。 要将数据发送到服务器,您可以这样做:

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.
 * 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. //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()。基本上类与存储过程类似。