Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 登入驗證實作:把帳號密碼送到伺服器端查驗 MySQL

編輯:Android 開發實例

本文記錄一個登入驗證功能的實作過程。需求是:Android 端輸入使用者名稱與密碼,送到伺服器端,由伺服器查詢 MySQL 資料庫確認帳號是否存在。首要問題自然是「Android 端的資料如何送到伺服器端」。

一、伺服器端:ManageServlet.java

 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 開發的讀者應該不難補上。

二、Android 端版面配置

 <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> 

三、MainActivity

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

四、負責送資料的 NewsService

 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請求
    */
   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;
   }
 }

因為需要連網,別忘了在 AndroidManifest.xml 加上權限:

 <uses-permission android:name="android.permission.INTERNET"/>

這份程式碼用在正式專案前必須修正的地方

上面的程式碼能把流程跑通,作為學習路徑很合適,但它距離「可以上線」還有一段距離,以下幾點請務必留意。

1. 千萬不要用 GET 傳密碼。GET 參數會完整出現在網址列、伺服器存取日誌、代理伺服器快取與瀏覽器歷史紀年中,等於把密碼明文寫進到處留存的地方。登入應該用 POST,並搭配 HTTPS。範例中的 doPost 是空的,實際上正好說明這個問題。

2. 必須使用 HTTPS。以 HTTP 傳送帳密,等於在網路上裸奔。若要正式上線,伺服器需配置憑證;開發階段用 HTTP:// 還要注意 Android 9.0 之後預設禁止明文流量,需在 network_security_config.xml 中明確開啟(且僅限開發用途)。

3. 密碼要加鹽雜湊後再比對。伺服器端不該存明文密碼,也不該用未加鹽的 MD5/SHA1。應使用 bcrypt、scrypt 或 Argon2 這類專為密碼設計的慢雜湊函式。

4. 不要在主執行緒做網路請求。Android 4.0 之後 NetworkOnMainThreadException 會直接讓程式崩潰。範例在 onClick 中同步呼叫網路方法,是必然出錯的。應改用 ExecutorService、Kotlin Coroutines、OkHttp 搭配非同步回呼,或 ViewModel + LiveData 的組合。

5. 那兩行 ISO8859-1 轉碼可以刪掉。這是舊專案為了解決中文亂碼留下的歷史寫法,在明確指定 UTF-8 編碼的前提下並不需要,反而可能引入新的亂碼問題。

6. 硬編碼 IP 不可行。192.168.1.104 這種內網位址只在本機網路有效,正式版應由設定檔或 BuildConfig 提供不同環境的 base URL。

7. 驗證成功後要維護登入狀態。真實的登入流程會由伺服器回傳 token(如 JWT 或 session id),客戶端保存它並在後續請求中帶上,而不是每次都送帳密。

把上述幾點補齊,這個登入功能才算真正可用。希望本文的實例與提醒對大家的 Android 開發有所幫助。

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