【问题标题】:DioError [DioErrorType.response]: Http status error [401]DioError [DioErrorType.response]:Http 状态错误 [401]
【发布时间】:2021-10-03 18:15:51
【问题描述】:
final dio = Dio();
    try {
      await dio.request(
        'https://api.example.com/api/v1/auth/validateMobile',
        data: {"phoneNo": "+91999999999"},
        options: Options(
          method: 'GET',
          headers: {
            HttpHeaders.authorizationHeader:
                'Bearer $token',
            'content-Type': 'application/json'
          },
        ),
      );
    } on DioError catch (e) {
      print(e);
    }
I/flutter (16336): DioError [DioErrorType.response]: Http status error [401]
I/flutter (16336): #0      DioMixin.assureDioError (package:dio/src/dio_mixin.dart:819:20)
I/flutter (16336): #1      DioMixin._dispatchRequest (package:dio/src/dio_mixin.dart:678:13)
I/flutter (16336): <asynchronous suspension>
I/flutter (16336): #2      DioMixin.fetch.<anonymous closure>.<anonymous closure> (package:dio/src/dio_mixin.dart)
I/flutter (16336): <asynchronous suspension>

即使我使用正确的令牌传递授权标头,我也会收到 401 错误。感谢您的帮助。

【问题讨论】:

    标签: flutter dart dio


    【解决方案1】:

    你应该像这样传递内容类型:

    HttpHeaders.contentTypeHeader: 'application/json'
    

    这是一个使用 this 代替 Dio 的示例:

    fetchSearchedNews(String searchParameter) async {
        final queryParameters = {
          'keywords': searchParameter,
        };
        final uri = Uri.https('$baseUrl', '/v1/search', queryParameters);
        final response = await http.get(uri, headers: {
          HttpHeaders.authorizationHeader:
              'YOUR KEY HERE',
          HttpHeaders.contentTypeHeader: 'application/json',
        });
        print(response.statusCode);
        if (response.statusCode == 200) {
          final items = json.decode(response.body);
          return NewsModel.fromJson(items).news;
        } else if (response.statusCode == 401) {
          throw Exception('Error 401');
        } else if (response.statusCode == 429) {
          throw Exception('Error 429');
        } else {
          throw Exception('null');
        }
      }
    

    【讨论】:

    • 试过还是不行
    • 用这个代替 Dio 看看它是否有效,我用一个例子编辑了我的答案
    猜你喜欢
    • 2021-08-31
    • 2022-11-29
    • 2022-12-23
    • 2020-03-22
    • 2020-04-18
    • 2023-03-25
    • 1970-01-01
    • 2020-05-22
    • 2021-08-19
    相关资源
    最近更新 更多