gpt4 book ai didi

json - 下载JSON时随机发生FormatException

转载 作者:行者123 更新时间:2023-12-03 03:35:20 25 4
gpt4 key购买 nike

我正在尝试从Heroku中托管的自定义API下载json数据,该代码在大多数情况下都可以正常工作,但是随机出现此错误

flutter: FormatException: Unexpected character (at character 1)
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum...
^

有时会出现此错误,但是如果我使用相同的链接重新下载相同的文件,则可以尝试所有操作,但仍然无法解决。

随机数据
import 'package:digest/random.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class RandomData extends ChangeNotifier {
List<Random> articles = [];


String utf8convert(String text) {
List<int> bytes = text.toString().codeUnits;
return utf8.decode(bytes);
}

Future addArticle(String url) async {
try {
http.Response _response = await http.get("http://randomapi.com/1?q=${url.trim()}");
var decoded = utf8convert(_response.body.toString());
var decodedData = jsonDecode(decoded);

articles.add(Random(
title: decodedData['title'],
dateAdded: 'Added ${monthNames[date.month-1]} ${date.day}, ${date.year}',
link: url,
imageUrl: decodedData['image'],
));
notifyListeners();

} catch (e) {
print(e);
}
}
}

JSON响应:
{
"item_id": 5,
"title": "Example Domain",
"image": "",
"authors": [],
"date": null,
"video_links": [],
"full_text": "Example Domain\n\nThis domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.\n\nMore information...",
}

请帮我解决这个问题。

最佳答案

我们最近在我们的应用程序中遇到了类似的问题。这是由服务器返回502 Bad Gateway状态引起的,因此响应中不包含JSON主体,而是包含HTML。您可以通过在解码之前检查状态代码来检查是否是这种情况:

if (_response.statusCode == 200) {
var decoded = // ...
} else {
print('Something went wrong; status: ${_response.statusCode}');
}

我很确定情况就是这样,因为您得到的异常显示HTML而不是预期的JSON: <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum...

关于json - 下载JSON时随机发生FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com