編輯:關於 Android 程式設計
曾經我覺得 Android 的網路通訊有點神奇,直到把網路基礎補起來,才發現一切都很有條理。這篇就透過一個小 Demo,把 GET 與 POST 兩種提交方式講清楚。
1. 用戶端可以抓取一個網頁的內容;
2. 用戶端把使用者名稱與密碼提交到 HTTP 伺服器,並在 Tomcat 主控台看到收到的內容。
package com.hwb.service;
import java.net.HttpURLConnection;
import java.net.URL;
public class HtmlContentService {
/**
* 依路徑取得資料
*/
public static byte[] getContent(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] arr = new byte[1024];
int res = -1;
while ((res = in.read(arr)) != -1) {
byteArrayOutputStream.write(arr, 0, res);
}
byteArrayOutputStream.close();
in.close();
return byteArrayOutputStream.toByteArray();
}
return null;
}
}這個方法就能完成一次完整的 HTTP 請求。回應先讀成位元組陣列,後續要怎麼處理都很自由——例如直接取得某個網站的原始碼。實務上更常見的是伺服器回傳 XML 或 JSON 字串,同樣先收為二進位資料,再交給解析器處理即可。
package com.hwb.control;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class UserServlet extends HttpServlet {
/** 接收兩個參數並在主控台印出 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println("name =" + name + ",password = " + password);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}package com.hwb.service;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class UserService {
/** 以 GET 方式提交資料 */
public static boolean sendDataByGet(String path, String userName, String passWord) {
try {
StringBuilder stringBuilder = new StringBuilder(path);
stringBuilder.append("?name=")
.append(URLEncoder.encode(userName, "UTF-8"))
.append("&password=")
.append(URLEncoder.encode(passWord, "UTF-8"));
URL url = new URL(stringBuilder.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/** 以 POST 方式提交資料 */
public static boolean sendDataByPost(String path, String userName, String passWord) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
StringBuilder builder = new StringBuilder();
builder.append("name=").append(URLEncoder.encode(userName, "UTF-8"))
.append("&password=").append(URLEncoder.encode(passWord, "UTF-8"));
byte[] arr = builder.toString().getBytes();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(arr.length));
OutputStream outputStream = conn.getOutputStream();
outputStream.write(arr);
if (conn.getResponseCode() == 200) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}用攔截工具比對兩次請求,差異一目了然:



GET 把參數接在網址後面,POST 則把參數放進請求本體。這帶來兩個實際影響:GET 的長度受網址限制、參數會暴露在網址列與伺服器日誌中;POST 則可承載更大的資料量,也不適合被瀏覽器快取或加入書籤。
先看 GET 的情況:

再看 POST:

很明顯,兩者都出現了亂碼。原因在於 Tomcat 預設以 ISO-8859-1 解碼請求參數。
POST 的處理相對簡單,只要明確指定編碼即可:
httpServletRequest.setCharacterEncoding("UTF-8");GET 比較麻煩,因為編碼發生在 URI 解析階段,此時 setCharacterEncoding() 已經來不及了。常見做法是自訂一個 Filter,包裝 request 並在 getParameter() 時做一次編碼轉換:
String value = super.getParameter(name);
return new String(value.getBytes("ISO-8859-1"), "UTF-8");完整實作如下:
package com.hwb.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter {
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) arg0;
HttpServletResponse httpServletResponse = (HttpServletResponse) arg1;
String method = httpServletRequest.getMethod();
if (method.equals("GET")) {
EncodingWrap encodingWrap = new EncodingWrap(httpServletRequest);
arg2.doFilter(encodingWrap, httpServletResponse);
} else if (method.equals("POST")) {
httpServletRequest.setCharacterEncoding("UTF-8");
arg2.doFilter(httpServletRequest, httpServletResponse);
}
}
}package com.hwb.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class EncodingWrap extends HttpServletRequestWrapper {
public EncodingWrap(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
if (name == null) return null;
String value = super.getParameter(name);
try {
return new String(value.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}以上大致就是完整流程。若有理解不到位之處,歡迎指正。
補充一點:如果是上傳檔案,建議改用 Socket 或 multipart 串流處理。HTTP 伺服器對單次請求的資料量通常設有上限,直接塞大檔案進表單很容易失敗。
OpenCV for Android 人臉識別入門:從相冊選圖到框選臉部
在 Android 上做人臉識別,OpenCV 是常見的選擇。透過 Java API,開發者可以較快完成環境建置與基本流程,例如從相冊選圖、轉換成 OpenCV 可用的
Android 智慧簡訊開發實戰:會話列表與選單動畫
畫面結構與互動目標 智慧簡訊的會話頁通常由兩部分組成:上方是可滾動的會話列表,下方則是操作選單。列表負責呈現最近的對話內容,而底部選單提供編輯、新增簡訊等功能。為了讓操作
Android 教學:Android 調用 JNI 方法及完整程式碼
Android 調用 JNI 方法及程式碼 JNI:Java Native Interface,用來實現 Java 與 C/C++ 的互通。 本文記錄在 Android
基於百度定位 SDK 實時計算移動距離的完整實現
前段時間因項目需求,我通過百度定位 SDK 實現了一個實時更新行駛距離的程序(類似出租車上的里程表)。看似簡單的「顯示當前位置」背後,要真正做到「實時累加移動距離」,其實