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

Android 網路通訊:GET、POST 與 HttpClient 提交參數實戰

編輯:關於 Android 程式設計

在 Android 應用中與伺服器交換資料是最基本的需求之一。本文整理了三種常見的 HTTP 提交方式:以 HttpURLConnection 實現的 GET、POST,以及以 Apache HttpClient 提交表單,並附上 XML 提交與伺服器端接收的範例。

一、HttpURLConnection 提交 XML

以 POST 方式上傳一段 XML 資料:

public static boolean sendXML(String path, String xml) throws Exception {
    byte[] data = xml.getBytes();
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(5 * 1000);
    conn.setDoOutput(true); // POST 提交必須允許對外輸出
    conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

    OutputStream outStream = conn.getOutputStream();
    outStream.write(data);
    outStream.flush();
    outStream.close();

    return conn.getResponseCode() == 200;
}

二、GET 請求

把參數拼接到網址後方,並對每個值進行 URL 編碼:

public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception {
    StringBuilder sb = new StringBuilder(path);
    sb.append('?');
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(entry.getKey()).append('=')
          .append(URLEncoder.encode(entry.getValue(), enc)).append('&');
    }
    sb.deleteCharAt(sb.length() - 1); // 移除多餘的 &

    URL url = new URL(sb.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(5 * 1000);
    return conn.getResponseCode() == 200;
}

三、POST 表單請求

把參數編碼後寫入輸出流,並設定 Content-Type 為 application/x-www-form-urlencoded:

public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception {
    StringBuilder sb = new StringBuilder();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append('=')
              .append(URLEncoder.encode(entry.getValue(), enc)).append('&');
        }
        sb.deleteCharAt(sb.length() - 1);
    }
    byte[] entitydata = sb.toString().getBytes();

    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(5 * 1000);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));

    OutputStream outStream = conn.getOutputStream();
    outStream.write(entitydata);
    outStream.flush();
    outStream.close();

    return conn.getResponseCode() == 200;
}

四、HttpClient 提交表單

使用 Apache HttpClient 提交,程式碼更為簡潔,也便於擴展 SSL、Cookie 等能力:

public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception {
    List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);
    HttpPost post = new HttpPost(path);
    post.setEntity(entitydata);

    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    return response.getStatusLine().getStatusCode() == 200;
}

伺服器端接收(Struts DispatchAction 範例)

伺服器端針對 GET 與 POST 分別處理,並特別注意 GET 傳送的中文參數需進行編碼轉換,以避免亂碼:

public ActionForward save(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    VideoForm formbean = (VideoForm) form;
    if ("GET".equals(request.getMethod())) {
        // GET 傳來的中文需先以 ISO-8859-1 還原,再以 UTF-8 解碼
        byte[] data = request.getParameter("title").getBytes("ISO-8859-1");
        String title = new String(data, "UTF-8");
        System.out.println("title:" + title);
    } else {
        // POST 參數可直接從表單取得
        System.out.println("title:" + formbean.getTitle());
    }
    return mapping.findForward("result");
}

實務上提醒:以上 HttpURLConnection、DefaultHttpClient 等屬於較早期的寫法,新專案建議優先採用 OkHttp 或官方推薦的網路庫,並務必把網路操作放在非主執行緒(背景執行緒)中執行,同時於清單檔加入 android.permission.INTERNET 權限。

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