編輯:關於 Android 程式設計
本文示範如何把 Android 端的表單數據上傳到後端 Web 應用。場景很簡單:界面有「視頻名稱」與「時長」兩個輸入框,點擊保存按鈕提交,服務端用 ManageServlet 接收。
public class ManageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String title = request.getParameter("title");
// Tomcat 預設以 ISO8859-1 解碼,需手動轉回 UTF-8
title = new String(title.getBytes("ISO8859-1"), "UTF-8");
String timelength = request.getParameter("timelength");
System.out.println("視頻名稱:" + title);
System.out.println("時長:" + timelength);
}
}
public class MainActivity extends Activity {
private EditText titleText;
private EditText lengthText;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.main);
titleText = (EditText) this.findViewById(R.id.title);
lengthText = (EditText) this.findViewById(R.id.timelength);
Button saveButton = (Button) this.findViewById(R.id.button);
saveButton.setOnClickListener(new ButtonClickListener());
}
private static class ButtonClickListener implements View.OnClickListener {
public void onClick(View v) {
String title = titleText.getText().toString();
String length = lengthText.getText().toString();
boolean result = NewsService.save(title, length);
Toast.makeText(getApplicationContext(),
result ? R.string.success : R.string.error, 1).show();
}
}
}
HTTP 協議中,GET 與 POST 都能提交參數。一般經驗法則是:2K 以內的數據兩者皆可,超過 2K 必須用 POST。GET 的特點是把參數拼在 URL 後面。
public class NewsService {
public static boolean save(String title, String length) {
String path = "https://192.168.1.100:8080/web/ManageServlet";
Map<String, String> params = new HashMap<String, String>();
params.put("title", title);
params.put("timelength", length);
try {
return sendGETRequest(path, params, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/* 拼接 GET 請求 */
private static boolean sendGETRequest(String path,
Map<String, String> params,
String encoding) throws Exception {
// 最終形如:...ManageServlet?title=xxx&timelength=90
StringBuilder url = new StringBuilder(path);
url.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
url.append(entry.getKey()).append("=");
url.append(URLEncoder.encode(entry.getValue(), encoding));
url.append("&");
}
url.deleteCharAt(url.length() - 1);
HttpURLConnection conn =
(HttpURLConnection) new URL(url.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
return conn.getResponseCode() == 200;
}
}
亂碼通常有兩個獨立成因,需要分別處理:
URLEncoder.encode(value, "UTF-8")。new String(title.getBytes("ISO8859-1"), "UTF-8")。參數一多,每個都手動轉碼既麻煩又易漏。更優雅的做法是寫一個 Filter,攔截所有請求統一處理。
public class EncodingFilter implements Filter {
public void destroy() { }
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if ("GET".equals(req.getMethod())) {
// GET 參數來自 URL,需要包裝後重新解碼
chain.doFilter(new EncodingHttpServletRequest(req), response);
} else {
req.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException { }
}
搭配的請求包裝類:
public class EncodingHttpServletRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public EncodingHttpServletRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
if (value != null) {
try {
value = new String(value.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) { }
}
return value;
}
}
在 web.xml 中把 URL Pattern 設為 /*,之後 Servlet 裡拿到的就都是正確的 UTF-8 字符串了。
先看一次真實的 POST 報文結構:
POST /web/ManageServlet HTTP/1.1 // 方法 / 路徑 / 協議版本 Accept: */* // 可接收的數據類型 Referer: https://192.168.1.100:8080/web/index.jsp // 來源路徑 User-Agent: ... // 客戶端標識 Content-Type: application/x-www-form-urlencoded // 提交數據的類型 Host: 192.168.1.100:8080 Content-Length: 26 // 數據總長度 Connection: Keep-Alive title=liming&timelength=90 // 實體正文
關鍵點在於:GET 把參數放 URL,POST 把參數放實體正文(body)。因此 POST 不受 URL 長度限制,也更適合傳遞較大或較敏感數據。
private static boolean sendPOSTRequest(String path,
Map<String, String> params,
String encoding) throws Exception {
StringBuilder data = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
data.append(entry.getKey()).append("=");
data.append(URLEncoder.encode(entry.getValue(), encoding));
data.append("&");
}
data.deleteCharAt(data.length() - 1);
}
byte[] entity = data.toString().getBytes();
HttpURLConnection conn =
(HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true); // 允許向服務端寫數據
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",
String.valueOf(entity.length));
OutputStream out = conn.getOutputStream();
out.write(entity);
// 注意:此時數據只寫入本地緩衝,需讀取響應碼後才真正送出
return conn.getResponseCode() == 200;
}
HttpClient 封裝了連接池、重試、Cookie 等細節,能勝任瀏覽器的大部分工作,代碼量顯著減少。
private static boolean sendHttpClientPOSTRequest(String path,
Map<String, String> params,
String encoding)
throws Exception {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
return response.getStatusLine().getStatusCode() == 200;
}
HttpURLConnection 是官方推薦的原生方案,實現透明、無需額外依賴,但連接管理要自己操心。HttpClient 功能強大但已於 API 22 被標記為 deprecated。如今的標準答案是 OkHttp 或 Retrofit:前者提供簡潔的同步/異步 API 與連接複用,後者則能用註解把接口聲明式地描述出來,並自動完成 JSON 序列化。本文的兩種寫法適合作為理解 HTTP 底層原理的入門,實際專案建議直接採用現代化框架。
另外别忘了:無論用哪種方式,網絡請求都必須放在子線程,並在 manifest 中申請 android.permission.INTERNET 權限。
拆解表單登入流程:動態 Token 與 HTTP 除錯的實務思路
很多非官方用戶端已經把官方網站的內容聚合得很完整,卻卡在最後一關:登入後的互動。大型網站為了抵禦惡意請求,會在表單裡塞入動態產生的驗證欄位,讓「照抄參數」這招完全失效。本
小豬的 Android 入門之路 Day 7 part 4:ContentProvider 內容提供者
轉載請註明出處:coder-pig 本節引言 在前面的學習中,我們已經接觸過一些存儲數據的方式,而這些方式大多是可以共享的。比如文件,我們可以把操作模式設置為 Conte
Android 自定義 Dialog 使用方法
Dialog 是 Android 中常見的互動元件,用於提示、確認、表單輸入或列表選擇。除了系統預設樣式,開發者也可以自定義布局,讓對話框更符合產品視覺。 自定義 Dia
Android 4.4 的外部儲存新模型:二級存儲與新增的存取 API
Android 4.4 對外部儲存(尤其是外置 SD 卡)的權限模型做了重大調整,很多原本能正常寫檔的 App 升級後突然寫不進去了。本文說明規則變化的內容與對應的新 A