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

Android 以 POST 方式提交資料到伺服器:與 GET 的完整對照

編輯:關於 Android 開發

Android 以 POST 方式提交資料到伺服器:與 GET 的完整對照

承接上一篇〈Android 採用 get 方式提交數據到服務器〉,這次我們在同一個專案上加入 POST 版本,讓兩種請求方式並排比較。

一、版面配置:兩個按鈕並列

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名"
        android:inputType="text" />

    <EditText android:id="@+id/et_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <Button android:onClick="LoginByGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GET方式登錄" />

    <Button android:onClick="LoginByPost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="POST方式登錄" />
</LinearLayout>

二、兩種請求的程式碼對照

package com.wuyudong.loginclient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText et_name;
    private EditText et_pwd;

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

        StrictMode.ThreadPolicy policy =
                new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    /** GET 方式 */
    public void LoginByGet(View view) {
        String name = et_name.getText().toString().trim();
        String pwd = et_pwd.getText().toString().trim();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "用戶名密碼不能為空", 0).show();
        } else {
            // 參數直接拼在網址後面
            String path = "https://169.254.168.71:8080/web/LoginServlet?username="
                    + name + "&password=" + pwd;
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
                        + "(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

                int code = conn.getResponseCode();
                if (code == 200) {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        bos.write(buffer, 0, len);
                    }
                    String result = new String(bos.toByteArray());
                    is.close();
                    Toast.makeText(this, result, 0).show();
                } else {
                    Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "請求失敗,請檢查 logcat 日誌控制台", 0).show();
            }
        }
    }

    /** POST 方式 */
    public void LoginByPost(View view) {
        String name = et_name.getText().toString().trim();
        String pwd = et_pwd.getText().toString().trim();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "用戶名密碼不能為空", 0).show();
        } else {
            try {
                String path = "https://169.254.168.71:8080/web/LoginServlet";
                // 1. 定義請求 url
                URL url = new URL(path);
                // 2. 建立一個 http 連接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 3. 設置請求參數
                conn.setRequestMethod("POST");
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
                        + "(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");

                String data = "username=" + name + "&password=" + pwd;
                conn.setRequestProperty("Content-Length", data.length() + "");
                conn.setConnectTimeout(5000); // 連接超時
                conn.setReadTimeout(5000);    // 讀取超時

                // 4. 一定要記得設置,把數據以流的方式寫給服務器
                conn.setDoOutput(true);
                conn.getOutputStream().write(data.getBytes());

                int code = conn.getResponseCode();
                if (code == 200) {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        bos.write(buffer, 0, len);
                    }
                    String result = new String(bos.toByteArray());
                    is.close();
                    Toast.makeText(this, result, 0).show();
                } else {
                    Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "請求失敗,請檢查 logcat 日誌控制台", 0).show();
            }
        }
    }
}

三、關鍵差異逐條對照

1. 參數位置:GET 把參數接在網址後(?username=...&password=...);POST 則透過要求主體(request body)傳送,網址保持乾淨。

2. 請求方法設定:conn.setRequestMethod("POST"),字串必須大寫。

3. Content-Type:POST 表單需明確宣告 application/x-www-form-urlencoded,伺服器才知道怎麼解析 body。

4. setDoOutput(true):這是最容易漏掉的一步。少了它,getOutputStream() 寫入的內容不會真正送出,伺服器收到的參數會是空的。

5. 逾時設定:setConnectTimeout() 與 setReadTimeout() 建議一定要設。不設的話在網路不佳時會無限期等待,實務上非常容易踩到 ANR。

6. 編碼問題:範例中的中文若出現亂碼,通常是兩端編碼不一致所致。正式專案應統一以 UTF-8 編碼,並對每個參數值做 URL Encode。

7. 安全性:GET 的參數會留在瀏覽器歷史、代理伺服器與存取日誌裡,密碼等敏感資訊不該走 GET。但 POST 本身也只是「不顯示在網址列」而已,傳輸內容仍是明文——真正解決之道是全程使用 HTTPS。

另外提醒,範例中的 StrictMode 設定只是為了讓教學程式碼能直接跑起來。正式環境請把網路操作移到工作執行緒,並在 HttpURLConnection 使用完畢後確實關閉串流,或改用 OkHttp、Retrofit 等成熟客戶端來處理連線管理與重試邏輯。

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