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

Android 使用 HTTPPost 提交資料到伺服器

編輯:關於 Android 程式設計

在 Android 應用與伺服器互動時,若需要傳送較多或較敏感的中文字串資料,使用 HTTP POST 請求會比 GET 更合適。以下示範如何以 DefaultHttpClient 搭配 NameValuePair 組裝表單參數並提交。

public void send() {
    HttpPost request = new HttpPost("https://192.168.1.8:8080/AndroidWeb/InsertServlet");

    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    BasicNameValuePair im = new BasicNameValuePair("imageid", imageid + "");
    BasicNameValuePair un = new BasicNameValuePair("uname", name.getText() + "");
    BasicNameValuePair pw = new BasicNameValuePair("password", password.getText() + "");

    String sex;
    if (sex_man.isChecked()) {
        sex = "M";
    } else {
        sex = "W";
    }
    BasicNameValuePair sx = new BasicNameValuePair("sex", sex);
    BasicNameValuePair br = new BasicNameValuePair("birthday", birthday.getText() + "");

    parameters.add(un);
    parameters.add(im);
    parameters.add(pw);
    parameters.add(sx);
    parameters.add(br);

    HttpEntity en;
    try {
        en = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
        request.setEntity(en);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    DefaultHttpClient dhc = new DefaultHttpClient();
    try {
        HttpResponse response = dhc.execute(request);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

重點說明

  • 使用 NameValuePair 將每個欄位組裝成鍵值對,再統一加入 parameters 清單。
  • UrlEncodedFormEntity 指定 UTF-8 編碼,可避免中文亂碼。
  • 透過 request.setEntity() 將表單資料掛載到 POST 請求上,再由 client.execute() 送出。

需要提醒的是,DefaultHttpClient 與 AndroidHttpClient 在較新的 Android 版本中已被標記為不建議使用,且網路請求應放在背景執行緒中進行,切勿在主執行緒(UI Thread)直接執行,以免觸發 NetworkOnMainThreadException。新專案建議改用 HttpURLConnection 或 OkHttp 等方案。

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