嗨,我试着用从因特网上获取数据用flutter,只要response.body中的所有字符都是英语,一切都很好,但是我用persian/arabic字符得到了这些结果。
链接到我正在测试的页面:http://mobagym.com/media/mobagym-app-info/farsi.html (我也用其他urls测试过它,我的api得到了相同的结果)
这是我的代码(我还尝试在Text Widget中显示结果):
static Future<String> loadFarsi() async{
final response = await http.get("http://mobagym.com/media/mobagym-app-info/farsi.html",headers:{"charset":"utf-8","Accept-Charset":"utf-8"});
print(response.body);
return response.body;
}我已经试过移除标题,但还是没有运气。
final response = await http.get("http://mobagym.com/media/mobagym-app-info/farsi.html");这是我在android工作室的日志:
Performing hot reload...
Reloaded 7 of 507 libraries in 1,333ms.
I/flutter (23060): <html>
I/flutter (23060): <head>
I/flutter (23060): <meta charset="utf-8"/>
I/flutter (23060): </head>
I/flutter (23060): <body>Ø³ÙØ§Ù Ø³ÙØ§Ù ÙØ±Ù اÛپسÙÙ</body>
I/flutter (23060): </html>这部分是错误的:“”(国家地理信息系统)、“国家地理信息系统”()、“国家统计调查”、“国家统计数据汇编”、“国家统计数据集”、“国家统计数据汇编”、“国家外汇管理局”、“
虽然像这样的东西是实际文本:سلامسلاملرمایپسوم
安卓手机Xperia z3 plus (Android6.0)的测试
使用Android:3.1.2
使用颤振:flutter_windows_v0.3.2-beta
结果显示文本小部件中的文本:

发布于 2018-05-13 19:07:26
web服务器的Content-Type头是Content-Type: text/html。注意,这不包括charset后缀。它应该说是Content-Type: text/html; charset=utf-8。当被要求解码字符时,package:http客户端将查找此字符集。如果缺少,默认为LATIN1 (不是utf-8)。
正如您所看到的,在请求上设置头没有帮助,因为解码是由响应完成的。幸运的是,有一个简单的解决办法。只需对字节进行解码就可以像这样把自己串起来。
Future<String> loadFarsi() async {
final response =
await http.get("http://mobagym.com/media/mobagym-app-info/farsi.html");
String body = utf8.decode(response.bodyBytes);
print(body);
return body;
}发布于 2021-01-11 12:32:28
为了保持干净,您可以编写像jsonDecodeUtf8这样的实用程序函数:
json_util.dart
dynamic jsonDecodeUtf8(List<int> codeUnits,
{Object reviver(Object key, Object value)}) =>
json.decode(utf8.decode(codeUnits), reviver: reviver);并把它当作:
String body = jsonDecodeUtf8(response.bodyBytes);https://stackoverflow.com/questions/50318681
复制相似问题