Servlet 容器預設以 ISO-8859-1 解碼 URL 參數,導致中文變「????」。標準三步走轉碼:
String utf8Param = request.getParameter("name"); // 實為 ISO-8859-1 位元組序列
byte[] bytes = utf8Param.getBytes("ISO-8859-1"); // 還原原始位元組
String gb2312 = new String(bytes, "GB2312"); // 按真實編碼重組
若容器已支援 request.setCharacterEncoding("UTF-8")(Tomcat 5+ 需在 server.xml 設 URIEncoding="UTF-8"),可直接取得正確字串。
網路流可能分多次到達,單次 read() 不保證讀滿,必須循環累積:
ServletInputStream in = request.getInputStream();
int size = request.getContentLength();
byte[] buffer = new byte[4096];
byte[] result = new byte[size];
int offset = 0, read;
while (offset < size && (read = in.read(buffer)) != -1) {
System.arraycopy(buffer, 0, result, offset, read);
offset += read;
}
// result 即完整請求體
善用 ByteArrayOutputStream 自動擴容:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
baos.write(buf, 0, len);
}
byte[] data = baos.toByteArray();
BufferedInputStream 包裝提升效能。