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

Android 用戶端與伺服器互動實作:以登入為例(IntentService + Servlet)

編輯:關於 Android 程式設計

這陣子研究了 Android 用戶端要怎麼跟伺服器互動,發現概念上和 Web 開發其實相當接近。以下整理一份登入範例,後端用 Servlet,前端以 IntentService 負責背景請求。

1. 後端:Servlet

後端用一個簡單的 Servlet 即可,同時支援 GET 與 POST,最後回傳一個 flag 字串給前端:true 代表登入成功,false 代表失敗。

部署前別忘了在 web.xml 中配置,特別注意 servlet-name 在 <servlet> 與 <servlet-mapping> 兩處必須一致,否則會找不到路徑。

<servlet>
    <servlet-name>helloWorld</servlet-name>
    <servlet-class>com.zhongzhong.wap.action.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>helloWorld</servlet-name>
    <url-pattern>/queryOrder</url-pattern>
</servlet-mapping>
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        boolean flag = false;
        String userName = req.getParameter("un");
        String password = req.getParameter("pw");

        if ("htp".equals(userName) && "123".equals(password)) {
            flag = true;
        }

        System.out.println("userName:" + userName + " password:" + password);
        out.print(flag);
        out.flush();
        out.close();
    }
}

範例在 MyEclipse 建立 Web 專案並部署到 Tomcat,方便 Android 用戶端連線測試。實務上請注意:帳密不應以純文字傳輸與比對,正式環境務必改用 HTTPS,並在後端以加鹽雜湊比對密碼。

2. 前端:兩個 Activity

在 ADT 建立 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="HelloWorld登陸示例" />

    <EditText
        android:id="@+id/et_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp"
        android:ems="10"
        android:hint="請輸入賬號" />

    <EditText
        android:id="@+id/et_psw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_user"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_psw"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp"
        android:text="登陸" />

</RelativeLayout>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".NaviActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"
        android:text="登陸成功" />

</RelativeLayout>

3. HTTP 工具類別

把 GET 與 POST 請求收攏到一個工具類別,並統一處理狀態碼:

package com.example.logindemo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpUtil {

    public static HttpClient httpClient = new DefaultHttpClient();
    public static final String BASE_URL = "https://192.168.3.14:8090/HelloWord/";

    /**
     * @param url 請求的 URL
     * @return 伺服器回應字串
     */
    public static String getRequest(String url) throws Exception {
        HttpGet get = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(get);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(httpResponse.getEntity());
        } else {
            Log.d("服務器響應代碼",
                    String.valueOf(httpResponse.getStatusLine().getStatusCode()));
            return null;
        }
    }

    /**
     * @param url      請求的 URL
     * @param rawParams 請求參數
     * @return 伺服器回應字串
     */
    public static String postRequest(String url, Map<String, String> rawParams)
            throws Exception {
        HttpPost post = new HttpPost(url);

        // 參數較多時可以封裝成 NameValuePair 清單
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : rawParams.keySet()) {
            params.add(new BasicNameValuePair(key, rawParams.get(key)));
        }

        post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse httpResponse = httpClient.execute(post);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(httpResponse.getEntity());
        }
        return null;
    }
}

4. IntentService 背景服務

IntentService 會以佇列方式把請求的 Intent 排隊,再開啟一個 worker thread 依序處理。對非同步的 startService 請求,它會處理完一個再處理下一個,因此很適合這種「一次一件」的耗時工作。

package com.example.logindemo;

import java.util.HashMap;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class ConnectService extends IntentService {

    private static final String ACTION_RECV_MSG = "com.example.logindemo.action.RECEIVE_MESSAGE";

    public ConnectService() {
        super("TestIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // 從主線程傳入的帳號與密碼
        String username = intent.getStringExtra("username");
        String password = intent.getStringExtra("password");

        boolean flag = doLogin(username, password);
        Log.d("登錄結果", String.valueOf(flag));

        // 透過廣播把結果送回 UI 線程
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(ACTION_RECV_MSG);
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        broadcastIntent.putExtra("result", String.valueOf(flag));
        sendBroadcast(broadcastIntent);
    }

    /** 定義發送請求的方法 */
    private Boolean doLogin(String username, String password) {
        String strFlag = "";

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("un", username);
        map.put("pw", password);

        String url = HttpUtil.BASE_URL + "queryOrder?un=" + username + "&pw=" + password;

        Log.d("url", url);
        try {
            strFlag = HttpUtil.postRequest(url, map);   // POST 方式
            // strFlag = HttpUtil.getRequest(url);      // GET 方式
            Log.d("服務器返回值", strFlag);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strFlag.trim().equals("true");
    }
}

5. Manifest 註冊

要把 IntentService 註冊進去,同時別忘了開啟網路權限:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.logindemo"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <application>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".NaviActivity" />

        <service android:name="com.example.logindemo.ConnectService" />
    </application>

</manifest>

6. 登入頁處理

按鈕監聽中透過 Intent 把帳密傳給 Service;接收廣播的類別再用 Intent 跳轉下一個 Activity。特別注意:動態註冊的廣播接收器在使用完畢後一定要註銷,否則會丟出 Are you missing a call to unregisterReceiver()? 的例外。

package com.example.logindemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final String ACTION_RECV_MSG = "com.example.logindemo.action.RECEIVE_MESSAGE";

    private Button loginBtn;
    private EditText et_username;
    private EditText et_password;
    private String userName;
    private String passWord;
    private MessageReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        // 動態註冊廣播接收器
        IntentFilter filter = new IntentFilter(ACTION_RECV_MSG);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new MessageReceiver();
        registerReceiver(receiver, filter);
    }

    private void initView() {
        et_username = (EditText) findViewById(R.id.et_user);
        et_password = (EditText) findViewById(R.id.et_psw);
        loginBtn = (Button) findViewById(R.id.btn_login);

        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (matchLoginMsg()) {
                    Intent msgIntent = new Intent(MainActivity.this, ConnectService.class);
                    msgIntent.putExtra("username", et_username.getText().toString().trim());
                    msgIntent.putExtra("password", et_password.getText().toString().trim());
                    startService(msgIntent);
                }
            }
        });
    }

    /** 輸入資料的基礎校驗 */
    protected boolean matchLoginMsg() {
        userName = et_username.getText().toString().trim();
        passWord = et_password.getText().toString().trim();

        if (userName.equals("")) {
            Toast.makeText(MainActivity.this, "賬號不能為空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (passWord.equals("")) {
            Toast.makeText(MainActivity.this, "密碼不能為空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /** 接收登入結果 */
    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("result");
            Log.i("MessageReceiver", message);

            if ("true".equals(message)) {
                startActivity(new Intent(MainActivity.this, NaviActivity.class));
                finish();
                context.unregisterReceiver(this);   // 記得註銷
            } else {
                Toast.makeText(MainActivity.this, "用戶名或密碼錯誤,請重新輸入!",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

運行結果

架構檢討與現代寫法建議

這個範例清楚示範了「UI 線程發請求 → 背景線程處理 → 廣播回傳結果」的閉環,但放在今天的專案裡有幾個地方值得調整:

  • org.apache.http 在 Android 6.0 之後已被移除,現行專案請改用 HttpURLConnection 或 OkHttp。
  • IntentService 在 API 30 已標記為 deprecated,背景工作建議改用 WorkManager 或 Kotlin Coroutines。
  • 以廣播傳遞敏感資料並不安全(同 App 內其他元件都能收到),可改用 ViewModel + LiveData 或 Result API。
  • 登入結果建議回傳結構化資料(如 JSON)並搭配統一的錯誤碼,而非單一字串 flag。

觀念是相通的:把網路請求從主線程移開、把結果安全地送回 UI,只是實作工具隨平台演進而改變。

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