Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 透過 JSON 將資料寫入 MySQL 的完整實作(寫入篇)

編輯:關於 Android 程式設計

上一篇講了讀取,這篇來談寫入。Android 把本地資料(例如定位、感測器讀數)上傳到資料庫,流程是:把參數封裝成 POST 表單 → 送到 PHP → PHP 寫入 MySQL 並回傳結果。

一、封裝 JSONParser 類別

把 HTTP POST 的細節收在一個類別裡,主程式只要呼叫一行就能完成上傳:

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url by making HTTP POST
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // request method is POST
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            Log.d("json", json.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

注意建表單時明確指定了 HTTP.UTF_8,這是避免中文欄位上傳後變亂碼的關鍵。

二、在主程式中呼叫

params = new ArrayList<NameValuePair>();
// 這裡可以替換成你自己程式中的一些鍵值對
params.add(new BasicNameValuePair("time", "" + time));
params.add(new BasicNameValuePair("lat", "" + lat));
params.add(new BasicNameValuePair("lon", "" + lon));
params.add(new BasicNameValuePair("encyptiontype", encyptiontype));
params.add(new BasicNameValuePair("rssi", rssi));
params.add(new BasicNameValuePair("name", name));

JSONParser jsonParser = new JSONParser();
// 數據的 php 文件的路徑
String url_up = "******/文件名字.php";
try {
    JSONObject json = jsonParser.makeHttpRequest(url_up, "POST", params);
    Log.v("uploadsucceed", "uploadsucceed");
} catch (Exception e) {
    e.printStackTrace();
}

三、接收資料的 PHP 檔案

<?php
// array for JSON response
// 此處需要將數據庫名、表名還有密碼做相應修改,改成你自己的
$con = mysql_connect("localhost", "root", null);
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("a0722152915", $con);

$response = array();
include("conn.php");

// check for required fields
if (isset($_POST['time']) && isset($_POST['lat']) && isset($_POST['lon'])
        && isset($_POST['encyptiontype']) && isset($_POST['rssi']) && isset($_POST['name'])) {

    $time = $_POST['time'];
    $lat = $_POST['lat'];
    $lon = $_POST['lon'];
    $encyptiontype = $_POST['encyptiontype'];
    $rssi = $_POST['rssi'];
    $name = $_POST['name'];

    $result = mysql_query("INSERT INTO wifi_state(time, lat, lon, encyptiontype, rssi, name)
        VALUES('$time', '$lat', '$lon', '$encyptiontype', '$rssi', '$name')");
    echo $result;

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    echo json_encode($response);
}
?>

回傳一個帶有 success 與 message 的 JSON,Android 端就能明確知道寫入成功與否,而不是只能盲等。

四、Android 4.0 以上的注意事項

如果你的裝置是 Android 4.0 以上,需要加上這段程式碼,否則網路請求會直接拋出例外:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()
        // or .detectAll() for all detectable problems
        .penaltyLog()
        .build());

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());

4.0 以下的系統則不需要這段。不過要提醒的是,StrictMode 的設計初衷是幫助你找出問題,而不是用來「關掉警告」。正式專案請把網路請求移到背景執行緒(AsyncTask、執行緒池或 Kotlin 協程),而不是靠 penaltyLog() 把例外吞掉。

五、上傳成功的畫面

六、寫入功能的重點檢核清單

把這份範例落進真實專案前,請確認以下幾件事:

  • 用 PDO 或 MySQLi 的 prepared statement 取代字串拼接。範例中 VALUES('$time', '$lat', ...) 這種寫法完全沒有防禦 SQL Injection,任何能攔截到這個請求的人都能對你的資料庫下達任意指令。
  • 不要信任客戶端送來的資料。伺服器端應驗證欄位型別與範圍,例如緯度必須落在 -90~90、經度 -180~180。
  • 加 API 金鑰或 Token。否則任何人都能用一隻 curl 灌入假資料。
  • 為失敗情況設計重試。網路是不穩定的,寫入失敗應該有退避重試機制,而不是靜默丟棄。
  • 改用 mysqli 並設定 utf8mb4。才能正確處理 emoji 與罕用漢字。

讀取方向的實作請參考姊妹篇。兩篇合起來,就是 Android 與 MySQL 透過 JSON 溝通最基礎的完整拼圖;掌握這個骨架之後,替換成 Retrofit 或任何現代框架都只是形式上的調整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved