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

Android 登入驗證實作:客户端表單到 Servlet 的完整串接

編輯:關於 Android 程式設計

本文的範例來自一個實際專案中的登入驗證需求:使用者在 Android 端輸入帳號與密碼,送到伺服器端比對 MySQL 中的使用者資料。要完成這件事,第一步得先讓兩端的通路打通,以下依序說明伺服器端、Android 介面與送資料的 Service。

伺服器端: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 基礎的人接手應該不成問題。特別注意兩端的編碼都要設為 UTF-8,否則中文很容易變成亂碼。

Android 端:MainActivity.java

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>

負責送出資料的 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 請求
     * @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 端與伺服器端的資料通路就算打通了,希望本文對你的開發有所幫助。

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