編輯:關於 Android 程式設計
本文的範例來自一個實際專案中的登入驗證需求:使用者在 Android 端輸入帳號與密碼,送到伺服器端比對 MySQL 中的使用者資料。要完成這件事,第一步得先讓兩端的通路打通,以下依序說明伺服器端、Android 介面與送資料的 Service。
public class ManageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println("用戶名:" + name + " 密碼:" + password);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
這裡只示範把收到的參數印在主控台上,確認資料已經準確過來。真正的帳密比對與回應組裝,有 JSP/Servlet 基礎的人接手應該不成問題。特別注意兩端的編碼都要設為 UTF-8,否則中文很容易變成亂碼。
public class MainActivity extends Activity {
private EditText textname = null;
private EditText textpassword = null;
private Button button = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textname = (EditText) findViewById(R.id.name);
textpassword = (EditText) findViewById(R.id.password);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new mybuttonlistener());
}
class mybuttonlistener implements OnClickListener {
boolean result = false;
String name;
String password;
public void onClick(View v) {
try {
name = textname.getText().toString();
name = new String(name.getBytes("ISO8859-1"), "UTF-8");
password = textpassword.getText().toString();
password = new String(password.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
result = NewsService.save(name, password);
} catch (Exception e) {
e.printStackTrace();
}
if (result) {
Toast.makeText(MainActivity.this, R.string.ok, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
}
}
}
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/playname"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/password" />
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:hint="@string/playpass"
android:singleLine="true" />
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/submit" />
</LinearLayout>
</RelativeLayout>
public class NewsService {
/**
* 登入驗證
* @param name 帳號
* @param password 密碼
* @return
*/
public static boolean save(String name, String password) {
String path = "https://192.168.1.104:8080/Register/ManageServlet";
Map<String, String> student = new HashMap<String, String>();
student.put("name", name);
student.put("password", password);
try {
return SendGETRequest(path, student, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 送出 GET 請求
* @param path 請求路徑
* @param student 請求參數
* @return 是否成功
* @throws Exception
*/
private static boolean SendGETRequest(String path, Map<String, String> student, String ecoding) throws Exception {
// https://127.0.0.1:8080/Register/ManageServlet?name=1233&password=abc
StringBuilder url = new StringBuilder(path);
url.append("?");
for (Map.Entry<String, String> map : student.entrySet()) {
url.append(map.getKey()).append("=");
url.append(URLEncoder.encode(map.getValue(), ecoding));
url.append("&");
}
url.deleteCharAt(url.length() - 1);
System.out.println(url);
HttpsURLConnection conn = (HttpsURLConnection) new URL(url.toString()).openConnection();
conn.setConnectTimeout(100000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
return true;
}
return false;
}
}
<uses-permission android:name="android.permission.INTERNET"/>
三點實務提醒:一是把帳密放在 GET 的 query string 中會被記錄在伺服器日誌裡,正式環境請改用 POST 並全程走 HTTPS;二是網絡請求需放在背景執行緒,Android 4.0 以後主執行緒會直接拋例外;三是範例中的 HttpsURLConnection 搭配 http 協定其實並不會加密,這點在 production 上務必修正。
到此,Android 端與伺服器端的資料通路就算打通了,希望本文對你的開發有所幫助。
夜神安卓模擬器怎麼玩手遊?安裝、載入 APK 與實用功能
夜神是目前效能表現相當突出的一款安卓模擬器。與傳統方案相比,它基於 Android 4.4.2,同時相容 X86 與 AMD 架構,在效能、穩定性與相容性上都有明顯改善,
Android 常用選擇器組件 CalendarView、DatePicker、TimePicker 與 NumberPicker 使用大全
本文一起複習幾個常用的基礎 UI 組件。Android 對這些組件封裝得非常完善,基本上套上屬性就能直接用,極大減輕了開發者的負擔;當然如果想深入研究,這其中仍有不少值得
Android SQLite 實戰:判斷資料表是否存在與基礎 CRUD
本文示範如何在 Android 的 SQLiteDatabase 中判斷某張表是否已存在,並順手把資料庫的基本操作跑一遍。關於 SQLite 更完整的用法,可參考 And
Android 搖一搖震動效果 Demo 實作
前言 微信剛流行的時候,搖一搖還能拿來「那啥」,我也曾經半夜拿著手機晃啊晃。當時心裡最常冒出的念頭是:為什麼搖一下得用這麼大的力氣?本以為這是什麼人性化設計,後來才發現—