編輯:關於 Android 程式設計
上一篇我們講了 GET 方式,這次來聊聊它的「兄弟」——POST。相比把參數暴露在 URL 上的 GET,POST 通過請求體傳遞數據,更適合提交大量或敏感信息,例如密碼、表單等。本文延續登陸示例,完整演示 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方式提交」按鈕,讓兩種方式可以對比測試。
<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>
兩個按鈕分別綁定 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();
}
}
與 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 參數隱藏在請求體中,能傳輸更大量、更安全的數據。實際開發中,請根據場景靈活選擇。
Android 自訂 View 實作仿小米安全中心的檢測進度條
這次來模仿小米安全中心的檢測效果。 專案網址:https://github.com/niniloveyou/GradeProgressView 這個效果的使用場景其實不
ViewPagerIndicator 製作 Tab 標籤
用 ViewPagerIndicator 做出完整 Tab 體驗 ViewPagerIndicator 是一個常見的開源庫,可與 ViewPager 搭配,快速做出頂部
Android ListFragment 範例:列表點擊與 Fragment 間資料傳遞
範例目標 本範例使用 ListFragment 建立列表,點擊列表項目後,將資料傳給另一個 Fragment 顯示。這個流程能幫助理解 Fragment 與 Activi
深入 Android Handler:用消息佇列實作執行緒間通信 ITC
Handler 是操作執行緒內部消息佇列的類。正因為它能操作佇列,也就順帶成為執行緒間通信(ITC,Inter Thread Communication)的手段——這種方