【发布时间】: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 兄弟它在我这边崩溃了。我已经完成了干净。重新启动了我的设备。还是一样