【问题标题】:Exception has occurred. FormatException (FormatException: Unexpected character (at character 1) <HTML></HTML> ^ )发生异常。 FormatException (FormatException: 意外字符 (在字符 1) <HTML></HTML> ^ )
【发布时间】:2020-04-07 14:27:14
【问题描述】:

我正在创建一个新闻应用程序,我通过 JSON 获取我的数据,并且在每次运行我的应用程序时都会让我崩溃 (response HTTP) 我无法理解:

Exception has occurred. FormatException (FormatException: Unexpected character (at character 1 <HTML></HTML> ^ )

代码:

import 'package:http/http.dart' as http;
import 'dart:convert';

class Category {

  int id;
  String title;

  Category({ 
    this.id,
    this.title 
  });

  static Future<List<Category>> getCategories() async {

    http.Response response = await http.get("url JSON"); // <- Here carash

    Map<String, dynamic> map = json.decode(response.body);

    List<Category> list = [];

    for(var map in map['categories']){
      list.add(
        Category(id: map['id'], title: map['title'])
      );
    }
    return list;
  }

}

【问题讨论】:

  • 您确定您的 JSON URL 返回的是 JSON,而不是 HTML?

标签: flutter dart


【解决方案1】:

我认为您的请求有问题,api 没有处理该错误,并将错误作为 html 抛出,正如我猜想的那样。反正你解码的方式不对。

在进行 http 请求时要记住几点:

  • 最重要的是研究数据类型(HTML / JSON)和结构 数据。通过打印到控制台或使用 curl 请求或邮递员的好方法。
  • 始终确保用try - catch 包裹您的json.decode() 块,当出现错误时,您可以正确看到发生了什么 使用您的代码。
  • 确保您的响应状态码为 200。并相应地处理您的数据。
  • 在迭代解码的响应之前,确保它包含 价值。
  • 如果您不知道类型或不知道 当然,不使用静态类型来分配解码的响应主体使用 final(不要总是使用动态类型,我的建议仅适用于这种情况)。这将帮助您解决FormatException 所面临的情况。
  • 最后但并非最不重要的一点是,当您想要检查带有状态代码的错误消息时。例如, 检查expired jwt 时,您将获得500 作为状态码。 所以在那种情况下只检查状态码是不够的 因为500 表示internal server error

例如: 列表列表 = [];

try {
    final decodedBody = json.decode(response.body); // when you have error messages with response, you can also check message with status code

    debugPrint(decodedBody?.toString());

    if (response.statusCode == 200) {
        if (decodedBody != null && map['categories'] != null) { // you can also check the data type you want here ex: (map is List)
            for(var map in map['categories']){
              list.add(Category(id: map['id'], title: map['title']));
            }

            // Below is another thrilled way to do this

            // list = decodedBody.map['categories']((item) => Category(id: item['id'], title: item['title'])).toList();
        }
    }

} catch(e, _) {
    debugPrint(e.toString());
}

希望这对您有所帮助。请按照上述步骤操作,如果有任何其他错误,请告诉我。

【讨论】:

    【解决方案2】:

    您收到的响应不是 JSON,因此无法解码您的 JSON。

    您的服务器正在返回一些 HTML 标记,这意味着您可能请求了错误的 URL,请检查 PostMan 或浏览器中的 URL 并查看响应。

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 1970-01-01
      • 2021-03-30
      • 2019-09-04
      • 2020-03-07
      • 2022-11-07
      • 2021-10-20
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多