Flutter/Dart中如何将UTF8十六进制转换为希伯来字母
解决Flutter中ChatGPT API返回希伯来文乱码问题
问题原因
这种乱码是典型的编码解码错误:ChatGPT返回的是UTF-8编码的希伯来文,但Flutter请求处理时,错误地将响应体按Latin-1(ISO-8859-1)解码为字符串,导致UTF-8多字节字符被拆分为单个Latin-1字符显示(比如0xD7显示为"×",0x94显示为"¤")。curl和ChatGPT网页端正确处理了UTF-8编码,因此显示正常。
解决方案
1. 直接处理响应原始字节(推荐)
在Flutter中,不要使用response.body(默认会根据响应头自动解码,可能误判编码),而是获取原始字节后手动用UTF-8解码:
import 'dart:convert'; import 'package:http/http.dart' as http; Future<void> fetchHebrewResponse() async { final url = Uri.parse('https://api.openai.com/v1/chat/completions'); final headers = { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json; charset=UTF-8', }; final body = jsonEncode({ 'model': 'gpt-4o-mini', 'messages': [ { 'role': 'user', 'content': 'Act as a Hebrew assistant that returns and replies valid, iterable JSON response, and provide a meaningful sentence in Hebrew, with Hebrew letters - not hexadecimal, with key Sentence, along with the English translation, with key Translation, for the Hebrew word: "shalom"' } ] }); final response = await http.post(url, headers: headers, body: body); if (response.statusCode == 200) { // 手动用UTF-8解码原始响应字节 final rawResponse = utf8.decode(response.bodyBytes); final jsonData = jsonDecode(rawResponse); // 提取并解析返回的JSON内容 final content = jsonData['choices'][0]['message']['content']; final result = jsonDecode(content); String hebrewSentence = result['Sentence']; String translation = result['Translation']; print('希伯来文:$hebrewSentence'); print('英文翻译:$translation'); } else { print('请求失败:${response.statusCode}'); } }
2. 修复已获取的乱码字符串
如果已经得到了乱码的字符串(比如缓存或其他来源),可以将其转回原始字节后重新用UTF-8解码:
String fixGarbledHebrew(String garbledText) { // 将乱码字符转回UTF-8原始字节(每个字符对应一个UTF-8字节) List<int> utf8Bytes = garbledText.codeUnits.map((unit) => unit & 0xFF).toList(); return utf8.decode(utf8Bytes); } // 使用示例 String garbled = "××××× ××× ××¦× ×©× ×¢×××ת ××× ×§××צ×ת ×× ×××× ×ת."; String correctHebrew = fixGarbledHebrew(garbled); print(correctHebrew); // 输出正常显示的希伯来文
内容的提问来源于stack exchange,提问作者Colin G
相关产品推荐
相关产品推荐

