flutter DioError [DioErrorType.response]:HTTP状态错误[401]

zpf6vheq  于 2023-04-07  发布在  Flutter
关注(0)|答案(3)|浏览(279)
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错误,即使我通过授权头与正确的令牌。谢谢你的帮助。

yduiuuwa

yduiuuwa1#

使用这个参数沿着其他选项参数,它为我工作,我希望它为您工作了
dio.request(***,options:选项(...

Options (validateStatus: (_) => true)

如果不行,你可以试试这个

Options (
 validateStatus: (_) => true,
 contentType: Headers.jsonContentType,
 responseType:ResponseType.json,
)
mrphzbgm

mrphzbgm2#

你应该像这样传递content-type:

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');
    }
  }
kxeu7u2r

kxeu7u2r3#

解决方案很简单,用dio的try catch包围请求,如下所示

try{
  //put your dio request here....
} on DioError catch(e){
  // in case of a code that is not success, you can get it here through object 'e'
}

以后再谢我!

相关问题