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

Android 使用 POST 方式向服務器請求與提交數據實戰

編輯:關於 Android 程式設計

上一篇我們講了 GET 方式,這次來聊聊它的「兄弟」——POST。相比把參數暴露在 URL 上的 GET,POST 通過請求體傳遞數據,更適合提交大量或敏感信息,例如密碼、表單等。本文延續登陸示例,完整演示 POST 的實現。

第一步:後端 Servlet 同時支持 GET 與 POST

為了讓同一個 Servlet 既能處理 GET 又能處理 POST,我們在 doPost 中直接調用 doGet,復用登陸校驗邏輯。

package com.wzw.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username.equals("admin") && password.equals("123456")) {
            response.getWriter().println("success");
        } else {
            response.getWriter().println("failed");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

第二步:布局加入 POST 按鈕

在原有基礎上新增一個「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:layout_marginTop="10dp" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/et_username" android:hint="請輸入名字"/>
    <EditText android:layout_marginTop="10dp" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/et_password" android:hint="請輸入密碼"/>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:onClick="doGet" android:text="GET方式提交"/>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:onClick="doPost" android:text="POST方式提交"/>
</LinearLayout>

第三步:Activity 中實現兩種提交

兩個按鈕分別綁定 doGet 與 doPost,都在子線程中發起網絡請求,再切回主線程彈出結果。

public class MainActivity extends Activity {
    private EditText etUsername;
    private EditText etPassword;

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

    public void doGet(View v) {
        final String username = etUsername.getText().toString();
        final String password = etPassword.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String state = NetUtil.loginOfGet(username, password);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MainActivity.this, state, 0).show();
                    }
                });
            }
        }).start();
    }

    public void doPost(View v) {
        final String username = etUsername.getText().toString();
        final String password = etPassword.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String state = NetUtil.LoginOfPost(username, password);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MainActivity.this, state, 0).show();
                    }
                });
            }
        }).start();
    }
}

第四步:POST 的核心實現

與 GET 最大的不同在於:POST 需要調用 setDoOutput(true),並通過 getOutputStream() 把參數寫入請求體,而不是拼接在 URL 後面。

public static String LoginOfPost(String username, String password) {
    HttpURLConnection conn = null;
    try {
        URL url = new URL("https://192.168.1.4:8080/AndroidServer/LoginServlet");
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(5000);
        conn.setDoOutput(true); // POST 請求必須允許輸出

        // POST 請求的參數寫入請求體
        String data = "username=" + username + "&password=" + password;
        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();

        conn.connect();
        int code = conn.getResponseCode();
        if (code == 200) {
            InputStream is = conn.getInputStream();
            return getStringFromInputStream(is);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) { conn.disconnect(); }
    }
    return null;
}

GET 與 POST 各有千秋:GET 參數明文可見、便於書籤收藏,但有長度限制;POST 參數隱藏在請求體中,能傳輸更大量、更安全的數據。實際開發中,請根據場景靈活選擇。

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