關鍵問題:亂碼是「顯示層」問題還是「數據層」問題?
# 服務端響應頭缺少 charset 或編碼不匹配
Content-Type: application/json # 缺少 charset
# 或
Content-Type: application/json; charset=GBK # 中文環境常見
解決:服務端統一設置 `Content-Type: application/json; charset=utf-8`
// OkHttp 默認根據 Content-Type charset 解碼,缺失時按 UTF-8
// 強制指定編碼
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonString, JSON);
// 或自定義 Converter
class GsonResponseBodyConverter implements Converter {
public T convert(ResponseBody value) {
String json = value.string(); // 內部已按 charset 解碼
return new Gson().fromJson(json, type);
}
}
// build.gradle
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
// 或
compileOptions.encoding = "UTF-8"
// 1. 打印原始字節
byte[] rawBytes = responseBody.bytes();
Log.d("RAW", Arrays.toString(rawBytes));
// 2. 打印十六進制
String hex = bytesToHex(rawBytes);
Log.d("HEX", hex);
// 3. 嘗試不同編碼解碼
String utf8 = new String(rawBytes, StandardCharsets.UTF_8);
String gbk = new String(rawBytes, "GBK");
Log.d("UTF8", utf8);
Log.d("GBK", gbk);
結論:90% 情況下「個別字符亂碼」源於服務端響應編碼聲明缺失或不匹配。優先用瀏覽器/Postman 驗證原始響應,而非在 IDE 控制台猜測。