編輯:Android 開發實例
Android 用戶端存取架在 IIS 上的 ASP.NET 服務時,若尚未登入,ASP.NET 的 Form 整合驗證會把我們導向登入頁。輸入正確的帳號密碼後,才能進入主程式。
本案例中,用戶端與伺服器之間一律以 JSON 傳遞資料,用戶端再依回傳內容的欄位判斷目前的登入狀態。由於 Form 驗證的機制是把狀態存在 Cookie 裡,所以每次發出 HTTP 請求前,都必須先把上一次的 Cookie 帶上去。
先建立一個統一格式的回應 Model,因為每個請求都會回傳 JSON:
public class ResponseResult
{
/// <summary> 是否已登入 </summary>
public bool IsAuthenticated { get; set; }
/// <summary> 是否執行成功 </summary>
public bool IsSuccess { get; set; }
/// <summary> 登入帳號 </summary>
public string Identity { get; set; }
/// <summary> 執行結果訊息 </summary>
public object Result { get; set; }
}
Index 是需要通過驗證才能存取的 Action,加上 [Authorize] 標記;LogOn 是未登入時被導向的 Action;Register 則是登入 Action,帳密正確時寫入 Form 驗證 Cookie。
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return Json(new ResponseResult
{
Result = "登入成功",
IsAuthenticated = true,
IsSuccess = true,
Identity = this.User.Identity.Name
}, "text/html", JsonRequestBehavior.AllowGet);
}
public ActionResult LogOn()
{
return Json(new ResponseResult
{
Result = "您尚未登入",
IsSuccess = true
}, "text/html", JsonRequestBehavior.AllowGet);
}
public ActionResult Register(string account, string password)
{
if (account == "demo" && password == "123")
{
FormsAuthentication.SetAuthCookie(account, false);
return Json(new ResponseResult
{
Result = "登入成功",
IsSuccess = true,
IsAuthenticated = true,
Identity = account
}, "text/html", JsonRequestBehavior.AllowGet);
}
return Json(new ResponseResult
{
Result = "帳號或密碼錯誤"
}, "text/html", JsonRequestBehavior.AllowGet);
}
}
<authentication mode="Forms">
<forms loginUrl="~/Home/LogOn" timeout="2880" />
</authentication>
最後設定 IIS 並部署這個 MVC 網站。
整個用戶端的關鍵就在這個 HttpHelper。它做三件事:發請求、把回應讀成字串、在請求前後保存與附加 Cookie。
public abstract class HttpHelper {
private final static String TAG = "HttpHelper";
private final static String SERVER_URL = "https://192.168.1.104:180/Home/";
private static CookieStore cookieStore;
public static String invoke(String actionName, List<NameValuePair> params) {
String result = null;
try {
String url = SERVER_URL + actionName + "/";
HttpPost httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(entity);
}
DefaultHttpClient httpClient = new DefaultHttpClient();
// 請求前:把上次保存的 Cookie 帶上去
if (cookieStore != null) {
httpClient.setCookieStore(cookieStore);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}
result = builder.toString();
// 請求後:保存本次的 Cookie 供下次使用
cookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return result;
}
public static String invoke(String actionName) {
return invoke(actionName, null);
}
}
這個設計的重點:Cookie 必須是全域的,每次呼叫前附加、呼叫後保存,登入狀態才能跨請求延續。
兩個 Activity 都使用 AsyncTask 把網路請求移出 UI 執行緒,並在 onPreExecute() 顯示進度對話框、在 onPostExecute() 解析 JSON 並更新介面。
// 登入:送出帳密,成功後跳轉主畫面
protected String doInBackground(Void... arg0) {
String account = edtAccount.getText().toString();
String password = edtPassword.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("account", account));
params.add(new BasicNameValuePair("password", password));
return HttpHelper.invoke("Register", params);
}
// 主畫面:呼叫需要驗證的 Index,依 IsAuthenticated 判斷狀態
protected String doInBackground(Void... arg0) {
return HttpHelper.invoke("Index");
}
在 onPostExecute() 中,登入頁依 IsSuccess 決定是否跳轉;主畫面則依 IsAuthenticated 決定顯示身份資訊,或跳回登入頁。
最後別忘了在 AndroidManifest.xml 加上網路權限:
<uses-permission android:name="android.permission.INTERNET" />
整套機制的核心其實只有一句話:Form 驗證靠 Cookie 維持狀態,所以用戶端必須自己管好 Cookie 的生命週期。
自訂 ArcImageView:在 ImageView 上疊加半透明圓弧與弧形文字
最近接到一個視覺需求:要在 ImageView 上疊一層半透明圓弧,並讓文字沿著弧線排布。最自然的做法是自訂一個 ImageView,在 onDraw() 裡把圓弧與文字
Android JSON 解析器:從 JSON 結構到天氣資料讀取
JSON(JavaScript Object Notation)是一種輕量、易讀的資料交換格式。相較於 XML,它更適合行動裝置與網路 API,因為結構簡單、解析速度快,
Android手機衛士(十九):建立首次密碼設定畫面
本篇要完成的是手機衛士中「第一次設定密碼」的流程。當使用者首次進入手機防盜功能時,必須先建立一組密碼,後續才能進行驗證與保護。畫面配置這個頁面可以採用垂直 LinearL
Android 載入動畫:不確定進度的 ProgressBar 用法
使用者按下按鈕之後,若畫面兩三秒毫無反應,多半會以為 App 當機了。這時候一個小小的旋轉動畫就能解決問題。Android 的 ProgressBar 有兩種呈現方式:有