下载时随机出现 FormatException JSON

FormatException randomly occurs while downloading JSON

我正在尝试从托管在 Heroku 中的自定义 API 下载 json 数据,代码大部分时间都没有问题,但随机出现此错误

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

我有时会收到此错误,但如果我使用相同的 link 重新下载相同的文件,它会起作用,我尝试了所有方法,但仍然无法修复。

RandomData.dart

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-body 而是 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...