简体   繁体   English

通过 JSON 从 android 向服务器发送数据

[英]Send data from android to server via JSON

  1. I have MySQL database server我有 MySQL 数据库服务器
  2. I need to update and retrieve data to/from MySQL server via JSON我需要通过 JSON 从 MySQL 服务器更新和检索数据

So, I want to know how to do that, and I pretty confuse with this example statement:所以,我想知道如何做到这一点,我对这个示例语句很困惑:

HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");

This means I need to code my application that connect with PHP server before write php to connect to DB right?这意味着我需要编写与 PHP 服务器连接的应用程序,然后再编写 php 以连接到数据库,对吗?

To send data to server you could do this:要将数据发送到服务器,您可以这样做:

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());
    }  
}

then to send lets say:然后发送让我们说:

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

so then the AddAccelerationData.php file on server is:那么服务器上的 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();
?>

This is an example I used recently.这是我最近使用的一个例子。 Just to note in the php file.请注意 php 文件。 I import Connection.php this just deals with the connection to the database.我导入 Connection.php 这只是处理与数据库的连接。 So just replace that with your code for connecting to MYSQL db.因此,只需将其替换为连接到 MYSQL db 的代码即可。 Also I imported SendAPI.php (which you can just ignore)This was just my class for sending data.我还导入了 SendAPI.php (你可以忽略)这只是我的 class 用于发送数据。 Basically it contained some of the querys I wanted to use.基本上它包含一些我想使用的查询。 Such as sendAccelerationData().比如sendAccelerationData()。 Basically class was similar to that of stored procedures.基本上 class 类似于存储过程。

You do need to update and retrieve through JSON?您是否需要通过 JSON 更新和检索? If this is the case, you'll probably have to code some Web Service and such, (it won't necessarily be in PHP, could be Java, C#, whatever) If this is the case, you'll probably have to code some Web Service and such, (it won't necessarily be in PHP, could be Java, C#, whatever)

Look at this thread, it seem there is no way you can access MySql server directly from android, so indeed, you may need some Web development implement the JSON/XML middle layer to connect with android. Look at this thread, it seem there is no way you can access MySql server directly from android, so indeed, you may need some Web development implement the JSON/XML middle layer to connect with android.

Thread @ StackOverFlow Android + MySQL using com.mysql.jdbc.Driver Thread @ StackOverFlow Android + MySQL using com.mysql.jdbc.Driver

Since an Android application cannot connect directly to a MySQL server you need to write a kind of a "bridge".由于 Android 应用程序无法直接连接到 MySQL 服务器,因此您需要编写一种“桥”。

UPDATE: @see Femi's comment更新:@see Femi 的评论

Well, technically speaking, It could: http://developer.android.com/reference/javax/sql/package-summary.html好吧,从技术上讲,它可以: http://developer.android.com/reference/javax/sql/package-summary.html

But for security reasons a bridge is a mandatory choice IMHO.但是出于安全原因,恕我直言,桥梁是强制性选择。

One one the most popular approach is to use the http protocol for sending and reading data.一种最流行的方法是使用 http 协议来发送和读取数据。

Your city.php will contain the logic for connect and querying the database:您的city.php将包含连接和查询数据库的逻辑:

<?php
$db = mysql_connect(....);
//query...
echo json_encode($data);
?>

The Android app will connect trough your server and will parse the json output. Android 应用程序将通过您的服务器连接并解析 json output。

So yes, you need to write the server-side part and client side part (Android)所以是的,您需要编写服务器端部分和客户端部分(Android)

A really useful video: http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html一个非常有用的视频: http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html

Code sample with PHP as bridge and Android via http protocol: PHP 作为桥接器和 Android 通过 http 协议的代码示例:

http://www.helloandroid.com/tutorials/connecting-mysql-database http://www.helloandroid.com/tutorials/connecting-mysql-database

You can do it by using JDBC.您可以使用 JDBC 来完成。 I did an application that talked with MYSQL using JDBC standard API.我做了一个应用程序,使用 JDBC 标准 API 与 MYSQL 交谈。 Please bear in mind that not all connectors works, the only one I know is mysql-connector-java-3.0.17-ga-bin.jar.请记住,并非所有连接器都有效,我知道的唯一一个是 mysql-connector-java-3.0.17-ga-bin.jar。

You'll need to implement a pool of connections to speed up query response times cause JDBC put a little overhead to Android when building a connection to server, it takes 2 to 3 seconds to start but once connected works very fast.您需要实现一个连接池以加快查询响应时间,因为 JDBC 在建立与服务器的连接时会给 Android 带来一点开销,启动需要 2 到 3 秒,但一旦连接后工作速度非常快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM