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

以 HttpClient 實作 Android 登入連線(GET 與 POST)

編輯:關於 Android 程式設計

下面用一個登入的小範例,說明 Android 端如何以 HttpClient 分別用 GET 與 POST 呼叫同一支 Servlet。兩種方式的差別只在參數傳遞:GET 把帳密拼在網址後面,POST 則用 NameValuePair 清單打包成表單實體。

版面與事件入口

public class MainActivity3 extends ActionBarActivity {

    private EditText et_userName;
    private EditText et_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_userName = (EditText) findViewById(R.id.et_userName);
        et_password = (EditText) findViewById(R.id.et_password);
    }

    public void login(View view) {
        String str = et_userName.getText().toString();
        try {
            // 帳號可能含中文或特殊字元,先編碼
            str = URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String userName = str;
        final String password = et_password.getText().toString();

        // 網路操作必須放在子執行緒
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final boolean isSuccess = loginByPost(userName, password);
                    // 若改用 loginByGet(userName, password) 亦可

                    // runOnUiThread 會把操作排回主執行緒執行
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity3.this,
                                    isSuccess ? "成功了!!!" : "失敗了!!!",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

GET 方式

/**
 * HttpClient 以 GET 方式存取伺服器
 */
private Boolean loginByGet(String userName, String password) throws Exception {
    String url = "https://192.168.1.140:8080/Login/servlet/Login";
    String data = "?userName=" + userName + "&password=" + password;

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url + data);
    HttpResponse response = client.execute(get);

    int code = response.getStatusLine().getStatusCode();
    if (code == 200) {
        InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String text = reader.readLine();
        reader.close();
        is.close();
        return "SUCCESS".equals(text);
    }
    client.getConnectionManager().shutdown();
    return false;
}

POST 方式

/**
 * HttpClient 以 POST 方式存取伺服器
 */
boolean loginByPost(String userName, String password) throws Exception {
    String url = "https://192.168.1.140:8080/Login/servlet/Login";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // 以表單形式送出參數
    List<NameValuePair> list = new ArrayList<>();
    list.add(new BasicNameValuePair("userName", userName));
    list.add(new BasicNameValuePair("password", password));
    post.setEntity(new UrlEncodedFormEntity(list));

    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();
    if (code == 200) {
        InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String text = reader.readLine();
        reader.close();
        is.close();
        return "SUCCESS".equals(text);
    }
    client.getConnectionManager().shutdown();
    return false;
}

別忘了權限

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

另外提醒兩點:一是 POST 比 GET 適合傳送帳密,因為 GET 的參數會留在伺服器與代理的存取記錄裡;二是 Apache HttpClient 在較新的 Android 版本已被標記為 deprecated,新專案建議改用 HttpURLConnection 或 OkHttp,並記得連線逾時要設定,避免執行緒被無限期佔用。

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