处理Dart的API时的状态代码401

mi7gmzs6  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(107)

晚上好,我正在与这个bug斗争:

Status code: 401

Response body: {"code":401,"message":"Missing or invalid x-api-key in header, get value by clicking on Me button in top right in UI"}

字符串
我目前正在使用这个API:https://api.restpoint.io/doc-runs?docId=SwaggerUI&x-endpoint-key=a7050c2545984437b2029d013d8a2e34
以下是我到目前为止写的代码:

Future<Book> fetchBookReviews() async {
  var url = Uri.parse(ApiConstants.baseUrl + 'doc-runs?docId=SwaggerUI');
  var response = await http.get(
    url,
    headers: {
      'x-endpoint-key': ApiConstants.docRunsEndpoint,
      'x-api-key': 'a7050c2545984437b2029d013d8a2e34',
    },
  );

  if (response.statusCode == 200) {
    try {
      Map<String, dynamic> jsonResponse = jsonDecode(response.body);
      return Book.fromJson(jsonResponse);
    } catch (e) {
      print('Error decoding response: $e');
      print('Response body: ${response.body}');
      throw Exception('Failed to decode JSON');
    }
  } else {
    print('Status code: ${response.statusCode}');
    print('Response body: ${response.body}');
    throw Exception('Failed to load book review');
  }
}


我做错了什么,我如何将API数据从json转换为dart?

7xzttuei

7xzttuei1#

不知道这是否会帮助你,但试着这样做:

Future<Book> fetchBookReviews() async {
  try {
    var url = Uri.parse(ApiConstants.baseUrl + 'doc-runs?docId=SwaggerUI');
    var response = await http.get(
      url,
      headers: {
        'x-endpoint-key': ApiConstants.docRunsEndpoint,
        'x-api-key': 'a7050c2545984437b2029d013d8a2e34',
      },
    );

    Map<String, dynamic> extractedData = jsonDecode(response.body);
    Book book = Book.fromJson(extractedData);

    return book;

  } catch (error) {
    print('Error: $error');
    throw (error);
  }
}

字符串

相关问题