使用 http.get Flutter 检索的带有 Utf-8 字符集的无效阿拉伯字符 [英] Invalid Arabic characters With Utf-8 charset Retrived with http.get Flutter

查看:13
本文介绍了使用 http.get Flutter 检索的带有 Utf-8 字符集的无效阿拉伯字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在

解决方案

Web 服务器的 Content-Type 标头是 Content-Type: text/html.请注意,不包括 charset 后缀.应该说 Content-Type: text/html;字符集=utf-8.package:http 客户端在要求解码为字符时查找此字符集.如果缺少,则默认为 LATIN1(不是 utf-8).

如您所见,在 Request 上设置标头无济于事,因为它是 Response 进行解码.幸运的是,有一个简单的修复方法.只需像这样自己将字节解码为字符串即可.

未来loadFarsi() 异步 {最后回复=等待 http.get("http://mobagym.com/media/mobagym-app-info/farsi.html");String body = utf8.decode(response.bodyBytes);打印(正文);返回身体;}

Hi i'm trying to Fetch data from the internet in flutter and as long as all characters in response.body are English everything is fine but i get these results with persian/arabic characters.

Link to page i'm testing this with: http://mobagym.com/media/mobagym-app-info/farsi.html (I've also tested it with other urls and my api got the same results)

This is my code(I've also tried showing the result in a 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;
  }

I've tried Remove the headers and still no luck.

final response = await http.get("http://mobagym.com/media/mobagym-app-info/farsi.html");

This is my log from android studio:

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>

This part is wrong: سÙا٠سÙا٠Ùر٠اÛپسÙÙ

Though something like this is the actual text: سلام سلام لرم ایپسوم

Testing on Android Phone Xperia z3 plus ( Android 6.0)

Using Android studio : 3.1.2

Using flutter : flutter_windows_v0.3.2-beta

Result showing the text in a text widget:

解决方案

The web server's Content-Type header is Content-Type: text/html. Note that isn't including a charset suffix. It should be saying Content-Type: text/html; charset=utf-8. The package:http client looks for this charset when asked to decode to characters. If it's missing it defaults to LATIN1 (not utf-8).

As you've seen, setting the headers on the Request doesn't help, as it's the Response that does the decoding. Luckily, there's a simple fix. Just decode the bytes to String yourself like this.

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

这篇关于使用 http.get Flutter 检索的带有 Utf-8 字符集的无效阿拉伯字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆