【问题标题】:Format Exception when fetching data from API in flutterFlutter中从API获取数据时出现格式异常
【发布时间】:2021-01-14 07:26:50
【问题描述】:

我已经收到了

"formatexception (formatexception: unexpected character (at line 8, character 1) <!doctype html><html class="no-js" lang="en"><head>"

错误,我的应用程序崩溃了。 我正在尝试从“http://newsapi.org/v2/top-headlines?country=ph&apiKey=aae937474dd8475ca6d45d403cbcd71c”API 获取新闻数据。 它以前可以工作,但现在我得到了那个异常错误。

这是我未来的代码,这里有 jsondecode。它在代码的 jsonDecode 部分出错。

    String url =
        "http://newsapi.org/v2/top-headlines?country=ph&apiKey=aae937474dd8475ca6d45d403cbcd71c";
    var response = await http.get(url);
    var jsonData = jsonDecode(response.body);
    if (jsonData["status"] == "ok") {
      jsonData["articles"].forEach((element) {
        if (element["urlToImage"] != null && element["description"] != null) {
          news.add(
            Article(
              title: element["title"],  
              imgUrl: element["urlToImage"],
              author: element["author"],
              url: element["url"],
              description: element["description"],
              content: element["content"],
              publishedAt: DateTime.parse(element["publishedAt"]),
            ),
          );
        }
      });
    }
  }
}

【问题讨论】:

  • 这通常发生在http请求无效并且网站将自身重定向到错误页面或主页,甚至是最近的路径时。这很奇怪,因为我的情况没有发生错误。在浏览器上键入链接本身,因为它应该显示为实际的 html
  • API 活跃且良好。但是当我在颤动中解码它时,它就会崩溃。我会做些什么来让这个例外消失? @AntónioOliveira
  • 对其进行了测试,代码运行良好。
  • @MJMontes 兄弟它在我这边崩溃了。我已经完成了干净。重新启动了我的设备。还是一样

标签: api flutter


【解决方案1】:

您的请求返回错误页面 请检查这个将从 NewsAPI 获取新闻的示例 https://rrtutors.com/tutorials/Flutter-NewsApplication-ListVew-Search-Filter

【讨论】:

  • 我需要重新编写所有代码还是只需要更改 API 密钥?
猜你喜欢
  • 1970-01-01
  • 2021-06-19
  • 2014-03-04
  • 1970-01-01
  • 2019-10-10
  • 2012-09-23
  • 2022-12-14
  • 1970-01-01
相关资源
最近更新 更多