【问题标题】:Accessing REST API in Flutter with HTTP package使用 HTTP 包在 Flutter 中访问 REST API
【发布时间】:2021-03-13 13:52:10
【问题描述】:

我有一个需要从 Flutter 应用程序访问的 REST API。它来自 Spotify Web API。我将用于此的终端命令是

curl -X "GET" "https://api.spotify.com/v1/me/following?
type=artist&limit=50" -H "Accept: application/json" -H "Content-Type: 
application/json" -H "Authorization: Bearer (ACCESS TOKEN)"

哪个有效。在 Flutter 中,我已经导入了 import 'package:http/http.dart' as http 包和 import 'dart:convert'。我还有一个Future,如下

Future<String> getData() async {
    http.Response response = await http.get(
        Uri.https("api.spotify.com", "v1/me/following?type=artist&limit=50"),
        headers: {
          "Accept": "application/json",
          "Content-Type": "application/json",
          "Authorization":
              "Bearer (ACCESS TOKEN)"
        });

    Map dataMap = jsonDecode(response.body);
    print(dataMap);
  }

这导致{error: {status: 404, message: Service not found}} 这很奇怪,因为它在终端中完美运行。我做错了什么?

【问题讨论】:

    标签: rest flutter spotify


    【解决方案1】:

    您需要保持简单。 URL 可能存在一些问题。试试这个:

    Future<String> getData() async {
        http.Response response = await http.get(
            "https://api.spotify.com/v1/me/following?type=artist&limit=50",
            headers: {
              "Accept": "application/json",
              "Content-Type": "application/json",
              "Authorization":
                  "Bearer (ACCESS TOKEN)"
            });
    
        Map dataMap = jsonDecode(response.body);
        print(dataMap);
      }
    
    

    【讨论】:

    • 我不确定它最近是否已更改,但.get 将 Uri 作为地址而不是字符串。因此它给出了一个错误。把String改成Uri.https('api.spotify.com', 'v1/me/following?type=artist&limit=50'),还是报404错误。
    【解决方案2】:

    网络服务:

    class NetService {
      static Future<T?> getJson<T>(String url, {int okCode = 200, String? authKey, Map<String, String>? headers}) {
        var localHeaders = <String, String>{};
        
        localHeaders['Accept'] = 'application/json';
        localHeaders['Content-Type'] = 'application/json';
        if (authKey != null) localHeaders['Authorization'] = 'Bearer $authKey';
        if (headers != null) localHeaders.addAll(headers);
    
        return http.get(Uri.parse(url), headers: localHeaders)
          .then((response) {
            if (response.statusCode == okCode) {
              return jsonDecode(response.body) as T;
            }
            PrintService.showDataNotOK(response);
            return null;
          })
          .catchError((err) => PrintService.showError(err));
      }
    }
    

    主要:

    import 'dart:async';
    
    import 'package:_samples2/networking.dart';
    
    class Spotify {
      static const _oAuthToken = 'XXXXYYYYYZZZZ';
      static const _url = 'https://api.spotify.com/v1';
    
      static FutureOr<void> getUsersFollowedArtists() async {
        await NetService.getJson<Map<String, dynamic>>(_url + '/me/following?type=artist&limit=50', authKey: _oAuthToken)
          .then((response) => print(response))
          .whenComplete(() => print('\nFetching done!'));
      }
    }
    
    void main(List<String> args) async {
      await Spotify.getUsersFollowedArtists();
      print('Done.');
    }
    

    结果:

    {artists: {items: [], next: null, total: 0, cursors: {after: null}, limit: 50, href: https://api.spotify.com/v1/me/following?type=artist&limit=50}}
    
    Fetching done!
    Done.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2013-12-29
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      相关资源
      最近更新 更多