編輯:關於 Android 開發
最近在更新自己的專案,順手把專案裡用到的幾個簡單網路互動方式整理成一系列文章,Android 網路編程的內容因此變多了些。我盡量用最直白的方式說明,若有錯誤也歡迎留言指正。
這篇示範的是「Android 端輸入 → PHP 接口 → MySQL 入庫」這條最常見的資料上傳路徑。PHP 端程式碼我已經寫好,你只要複製到自己的伺服器即可測試;Android 端則記得把套件名稱換成自己的。
Android 端介面:

MySQL 資料庫:

執行後的資料表:

package com.example.insertphp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
// 接口位址
private String url = "https://10.17.64.8:8080/testregister/register.php";
private String a;
private String b;
private EditText et1;
private EditText et2;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.edtv);
et2 = (EditText) findViewById(R.id.edt);
btn = (Button) findViewById(R.id.bt);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
a = et1.getText().toString();
b = et2.getText().toString();
// 鍵名必須與接口中 POST 的鍵完全一致
params.add(new BasicNameValuePair("name", a));
params.add(new BasicNameValuePair("password", b));
JSONParser jsonParser = new JSONParser();
try {
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
Log.v("uploadsucceed", "uploadsucceed");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("輸入的第一個內容:" + a);
System.out.println("輸入的第二個內容:" + b);
}
});
// 以下為在 ICS 之後於主執行緒發網路請求的必要設定
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // 或用 .detectAll() 一次偵測所有問題
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
}
注意:這裡的接口位址是我本機伺服器,你在自己電腦測試時必須改成自己的位址。查詢方式:Win + R 輸入 cmd,執行 ipconfig/all,在結果中找 IPv4 位址即可。testregister 是我的專案目錄,register.php 是 PHP 檔。
特別注意:加入 list 時,鍵值對中的鍵名必須與接口 POST 的名稱一致,否則寫入的會是空資料。
順帶一提,上面這段 StrictMode 只是為了讓範例在主執行緒發請求時不報錯。正式專案應該把網路呼叫放到子執行緒(Thread、AsyncTask 或後續的 coroutine/RxJava),而不是關掉 StrictMode 的檢查。
package com.example.insertphp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() { }
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// 發送 HTTP 請求
try {
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);
}
// 轉為 JSONObject
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
別忘了加上網路權限:
<uses-permission android:name="android.permission.INTERNET"/>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/edtv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/edt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交" />
</LinearLayout>
<?php
// 連接本地資料庫 localhost,帳號 root,密碼為空
$con = mysql_connect("localhost", "root", "");
// 設定字元集
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
if (!$con) {
die(mysql_error());
}
mysql_select_db("testregister", $con);
?>
<?php
require 'Conn.php';
$response = array();
// POST 的 name 必須與 Android 端的鍵一致,否則不會寫入資料
if (isset($_POST['name'])) {
$nickname = $_POST['name'];
$password = $_POST['password'];
$query = mysql_query("INSERT INTO test_register(nickname, password)
VALUES ('$nickname', '$password')");
if ($query) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
}
?>
如果執行後 Logcat 出現類似成功上傳的訊息,大致就通了。

測試時用英文最省事;若必須傳中文,上述程式碼也能勝任,只要兩端字元集一致(這裡用 UTF-8,是最普遍且不常出問題的選擇)。若不行的話,先檢查資料庫、連線與表單三處的編碼是否統一。
需要說明的是,範例中的 mysql_* 系列函式在 PHP 5.5 起已被標記為過時,PHP 7 中更已完全移除,實際專案應改用 mysqli 或 PDO。同樣地,Android 端的 Apache HttpClient 在 API 23 之後也不再內建。
更重要的是安全性:把使用者輸入的字串直接拼進 SQL 敘述,等於敞開了 SQL Injection 的大門,密碼明文入庫也是重大風險。正確做法是用 PDO 的 prepared statement 綁定參數,並對密碼做加鹽雜湊(如 password_hash())。這裡保留原始寫法,是為了呈現最直白的資料流;實際上線前一定要補上這幾層防護。
水平有限就先寫這些,若有更好的做法,歡迎留言交流。
Android 屬性動畫詳解(下):ValueAnimator、ObjectAnimator 與兩個完整案例
上一篇講完了補間動畫,這一篇進入屬性動畫的核心。先看繼承關係: 視線自然會落在 ValueAnimator 和 ObjectAnimator 這兩個類上。ObjectA
ViewPager 實戰:打造可左右滑動的分頁介面
ViewPager 能夠模仿微信那樣實現左右滑屏切換頁面的效果。下面透過一個完整範例來說明其實現方式。 MainActivity 透過 View 物件作為 ViewP
深入解析 ListView 聯動:仿餓了麼點餐界面
透視雙 ListView 聯動的實現原理 本文將對「仿餓了麼點餐界面」中兩個 ListView 聯動的效果進行代碼層面的深入剖析。通過拆解大神的經典實現,既能方便自己日後
註冊介面設計與實作(二):註冊業務邏輯的實作
註冊介面設計與實作(二):註冊業務邏輯的實作 承接上一篇的註冊介面設計,本篇聚焦於註冊業務邏輯的實作。核心在於一個 checkform 方法,用來驗證表單:帳號不可為空、