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

Android 透過 HttpClient 存取伺服器 Servlet 實作登入

編輯:關於 Android 程式設計

本文示範一個登入頁面:輸入使用者名稱與密碼,登入成功後跳轉到主頁面,失敗時顯示錯誤訊息。傳遞參數時使用 BasicNameValuePair 的 List,並以 httpPost.setEntity 的方式送出,而不能用 HttpParams。

首先在登入按鈕的點擊事件中,建立 HttpClient 與 HttpPost,把使用者名稱與密碼打包成 NameValuePair 清單後編碼送出:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(strUrl);
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("username", userName.getText().toString()));
params.add(new BasicNameValuePair("password", password.getText().toString()));
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);

接著在接收端判斷狀態碼是否為 200,若成功則解析回傳的 JSON,取出 loginStatus 與 outMessage:

if (httpResponse.getStatusLine().getStatusCode() == 200) {
  result = EntityUtils.toString(httpResponse.getEntity());
  JSONTokener jsonParser = new JSONTokener(result);
  JSONObject jsonResult = (JSONObject) jsonParser.nextValue();
  String status = jsonResult.getString("loginStatus");
  String outMessage = jsonResult.getString("outMessage");
  if (status.equals("true")) {
    Intent i = new Intent(LoginActivity.this, MainActivity.class);
    i.putExtra("username", outMessage);
    startActivityForResult(i, FIRST_REQUEST_CODE);
  } else {
    errorMsg.setVisibility(View.VISIBLE);
    errorMsg.setText(outMessage);
  }
} else {
  errorMsg.setVisibility(View.VISIBLE);
  errorMsg.setText("網路連接問題。CODE:" + httpResponse.getStatusLine().getStatusCode());
}

最後別忘了以 try-catch 處理 JSONException、UnsupportedEncodingException、ClientProtocolException 與 IOException 等可能的例外。這樣就完成了一個以 HttpClient 對接伺服器 Servlet 的完整登入流程。

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