首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2ME

解決 J2ME 聯網中文亂碼:位元組陣列轉 UTF-8 字串關鍵技巧

     編輯:J2ME

問題現象

J2ME DataInputStream.read() 逐字元讀取回應,若伺服器回傳 UTF-8 中文,直接 new String(byte[]) 依平台預設編碼 (常為 ISO-8859-1) 會產生亂碼。

核心解法:指定 UTF-8 解碼

// 關鍵代碼片段
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);

完整 MIDlet 範例

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...
}

補充建議

  • 若伺服器回傳非 UTF-8 (如 Big5),需對應修改解碼字集。
  • 發送端亦需 URLEncoder.encode(param, "UTF-8") 並設定 Content-Type: application/x-www-form-urlencoded; charset=UTF-8。
  • 使用 ByteArrayOutputStream 累積完整位元組再一次解碼,效能優於逐字元 read()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved