1

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

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

我有时会收到此错误,但如果我使用相同的链接重新下载相同的文件,它可以工作,我尝试了一切,但仍然无法修复。

随机数据.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...",
}

请帮我解决这个问题。

4

1 回答 1

1

我们最近在我们的应用程序中遇到了类似的问题。它是由服务器返回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...

于 2020-04-24T15:33:05.610 回答