尝试发出经过身份验证的请求时 API 出现 Flutter 500 错误

Flutter 500 error on API when trying to make authenticated requests

我正在尝试发出经过身份验证的请求,但出现 500 错误。当我更改我的令牌时,我收到 401 错误,这意味着未经过身份验证。

这是我的代码:

import 'dart:convert';
import 'dart:io';
import 'myapp/models/apis/stocks.dart';
import 'package:http/http.dart' as http;

class StocksService {
  final String url = "https://api.collectapi.com/economy/hisseSenedi";

  Future<StocksModel?> fetchStocks() async {
    var res = await http.get(
      Uri.parse(url),      
      headers: {
        HttpHeaders.authorizationHeader:
            "apikey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      },
    );
    if (res.statusCode == 200) {
      var jsonBody = StocksModel.fromJson(jsonDecode(res.body));
      return jsonBody;
    } else {
      print("İstek başarısız oldu => ${res.statusCode}");
    }
  }
}

代码有问题吗?

你的header是错误的。我有一个简单的代码:

import 'package:wnetworking/wnetworking.dart';


class CollectApi {
  final _url = 'https://api.collectapi.com/economy';
  final _token = '1111111111111111111111111111111';
  /* ---------------------------------------------------------------------------- */
  CollectApi();
  /* ---------------------------------------------------------------------------- */
  Future<void> hisseSenedi() async {
    var result = await HttpReqService.get<JMap>(
      '$_url/hisseSenedi',
      auth: AuthType.apiKey,
      authData: MapEntry('Authorization', 'apikey $_token'),
    );

    print(result.toString().substring(0,100));
  }
}

void main(List<String> args) async {
  await CollectApi().hisseSenedi();
  print('Job done!');
}

输出:

{success: true, result: [{rate: 3.08, lastprice: 19.39, lastpricestr: 19,39, hacim: , hacimstr: ₺5.5
Job done!

wnetworking 包基于 http.