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>
I'm getting 401 error even though I'm passing authorization header with correct token. Thank you for your help.
Use this parameter along with other option parameters, it worked for me, I hope it works for you too
dio.request( ***, options: Options(...
Options (validateStatus: (_) => true)
If it does not work, you can try this
Options (
validateStatus: (_) => true,
contentType: Headers.jsonContentType,
responseType:ResponseType.json,
)
you should pass content-type like this:
HttpHeaders.contentTypeHeader: 'application/json'
here is an example of using this instead of 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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With