J2ME DataInputStream.read() 逐字元讀取回應,若伺服器回傳 UTF-8 中文,直接 new String(byte[]) 依平台預設編碼 (常為 ISO-8859-1) 會產生亂碼。
// 關鍵代碼片段
HttpConnection hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
DataOutputStream dos = hc.openDataOutputStream();
// ... 寫入請求體 ...
DataInputStream dis = new DataInputStream(hc.openInputStream());
byte[] buffer = new byte[1024]; // 視回應大小調整
int len = dis.read(buffer); // 一次讀取 (或循環讀取)
String content = new String(buffer, 0, len, "UTF-8"); // 關鍵:指定 UTF-8
// 顯示
Form form = new Form("Response");
form.append(content);
display.setCurrent(form);
public class EncodingMidlet extends MIDlet {
private Display display;
public void startApp() {
new Thread(() -> {
try {
String url = "https://example.com/api?param=中文";
HttpConnection hc = (HttpConnection) Connector.open(url);
DataInputStream dis = new DataInputStream(hc.openInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int n;
while ((n = dis.read(buf)) != -1) baos.write(buf, 0, n);
byte[] data = baos.toByteArray();
String result = new String(data, "UTF-8"); // 核心修正
display.setCurrent(new Form("Result").append(result));
} catch (Exception e) { e.printStackTrace(); }
}).start();
}
// pauseApp, destroyApp...
}
URLEncoder.encode(param, "UTF-8") 並設定 Content-Type: application/x-www-form-urlencoded; charset=UTF-8。ByteArrayOutputStream 累積完整位元組再一次解碼,效能優於逐字元 read()。