Flutter DioError [DioErrorType.RESPONSE]: Http status error [403] - flutter

I get this massage:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception:
DioError [DioErrorType.response]: Http status error [403]
Here is loginCall method:
Future<LoginModel?> loginCall(
String email,
String password,
) async {
Map<String, dynamic> json = {"email": email, "hashPass": password};
var response = await dio.post(baseUrl + "login", data: json);
print(response.data);
print(response.statusCode);
if (response.statusCode == 200) {
var result = LoginModel.fromJson(response.data);
print("gelen response: ${response.data}");
return result;
} else {
throw Exception("Error! ${response.statusCode}");
}
}

error 403 usually means unauthorized. Therefore, you are probably entering incorrect email and password combination.

Related

I don't know why im I getting DioError Http status error [400] when sending comment from flutter app to .net core api

I'm tryng to post a comment related to ceratin document in my app. I'm using .net core api and already have a working webb app. When i send comment I get an error saying:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: DioError [DioErrorType.response]: Http status error [400]
I have web app where comment section is working just fine and object that is sent in mobile app is same as in web app. Example here :
{documentId: 45, parentId: null, text: dsafd}.
ParentId is for replying to another comment, so for new comment it should be null.
This is method for posting comment
onCommentSend() async {
Client _client = Client();
var data = {
'documentId': widget.dokumentId ?? 0,
'parentId': null,
'text': commentController.text,
};
print(data);
var res = await _dokumentiService!.addComment(data);
print(res);
if(data== true){
print('Added comment');
} else {
print('not added');
}
}
And this is service method
Future<bool> addComment(komentar) async {
final response = await _client.post('/dokumenti/insertComment', data: komentar);
if(response.statusCode == 200) {
final jsonresponse = response.data;
print(komentar);
print(komentar);
return jsonresponse;
} else {
throw Exception('failed');
print(Exception);
}
}
You need to pass data like this inside data of request :
final response = await _client.post('/dokumenti/insertComment', data: jsonEncode(komentar));
and try this

flutter Unhandled Exception: DioError [DioErrorType.response]: Http status error [422]

I have an API which sends status 201 in case of a success and if there's any error with the submitted data it sends status 422 (Unprocessable Entity) with a JSON response.
{
"message": "The given data was invalid.",
"errors": {
"mobile": [
"The selected mobile is invalid."
]
}}
I am using Dio to post user credentials (mobile, password) if I enter the correct user credential I can fetch data from it but when I enter the wrong credential gives me this error:
Unhandled Exception: DioError [DioErrorType.response]: Http status error [422]
Dio code
userLogin(
String password,
String mobile,
) async {
try {
String url = "url";
Dio dio = Dio();
dio.options.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
var response = await dio.post(url, queryParameters: {
"password": password,
"mobile": mobile,
});
if (response.statusCode == 200) {
return response.data;
} catch (e) {
return e.toString();
}}
How I cloud handle error response and success?
If some of Http status codes in responses are approved then you could use validateStatus function in BaseOptions to make them valid for all dio requests.
Dio dio = Dio(
BaseOptions(
headers: {...},
validateStatus: (statusCode){
if(statusCode == null){
return false;
}
if(statusCode == 422){ // your http status code
return true;
}else{
return statusCode >= 200 && statusCode < 300;
}
},
)
);
or validateStatus function in Options of concrete request
var response = await dio.post(url,
queryParameters: {
"password": password,
"mobile": mobile,
},
options: Options(
responseType: ResponseType.json,
validateStatus: (statusCode){
if(statusCode == null){
return false;
}
if(statusCode == 422){ // your http status code
return true;
}else{
return statusCode >= 200 && statusCode < 300;
}
},
),
);
The catch method has to be added to the try. In your case it was added to if(response.statuscode ==200)
userLogin(
String password,
String mobile,
) async {
try {
String url = "url";
Dio dio = Dio();
dio.options.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
var response = await dio.post(url, queryParameters: json.encode({
"password": password??"",
"mobile": mobile??"",
}));
if (response.statusCode == 200) {
return response.data;
}
else{
print(response.data);
return "request failed";
}
}catch (e) {
return e.toString();
}
My Api response was this enter image description here
I have dealt with this method by allowing it BaseOptions
here is my post API code and bingo got the solution to problem
Future postApiResponse(
String url, dynamic data, bool tokentrue, String? token) async {
dynamic responceJson;
try {
// print('here 222');
if (kDebugMode) {
print('In Dio in try');
print(url);
print(data.toString());
print(tokentrue.toString());
print(token.toString());
print('In Dio in try');
}
Dio dio = Dio(BaseOptions(validateStatus: (statusCode) {
if (statusCode == 422) {
return true;
}
if (statusCode == 200) {
return true;
}
return false;
}));
if (tokentrue == true) {
// dio.options.headers['content-Type'] = 'application/json';
dio.options.headers['Accept'] = 'application/json';
dio.options.headers["authorization"] = "Bearer $token";
} else {
dio.options.headers['Accept'] = 'application/json';
}
// print('responceJson.toString()');
Response responce = await dio
.post(
url,
data: data,
)
.timeout(const Duration(seconds: 20));
debugPrint('.toString()');
responceJson = returnResponce(responce);
debugPrint(responce.toString());
} on DioError catch (e) {
returnExceptionError(e);
}
return responceJson;
}
DioError [DioErrorType.response]: Http status error [422]
The Solution :)
Dio dio = Dio(
BaseOptions(
headers: {...},
validateStatus: (statusCode){
if(statusCode == null){
return false;
}
if(statusCode == 422){ // your http status code
return true;
}else{
return statusCode >= 200 && statusCode < 300;
}
},
)
);

Flutter Http Multi part Request get response body

I want to get response data from MultipartRequest
I uploaded an image to service and I should get image URL in response but I got an Bad state: Stream has already been listened to.
this My code snippet
//upload image
Future<ApiResponse> uploadOrderPic(
{required String orderID,
required File image,
required String type}) async {
ApiResponse apiResponse = ApiResponse();
var token = await getToken();
try {
var request = http.MultipartRequest(
"POST", Uri.parse(uploadPicUrl));
request.files
.add(await http.MultipartFile.fromPath('image', image.path));
request.fields['id'] = '1084';
request.fields['type'] = 'invoice';
request.headers['${HttpHeaders.authorizationHeader}'] = 'Bearer $token';
request.send().then((value) => http.Response.fromStream(value).then((onValue) {
try {
// get response...
logger.i(value.stream.bytesToString());
} catch (e) {
// handle exception
logger.e(e);// This catch Stream has already been listened to.
}
}));
} catch (e) {
logger.e(e);
apiResponse.error = serverError;
}
return apiResponse;
}
the logger.i(value.statusCode); print status code is 200(ok)
but
logger.i(value.stream.bytesToString()); print exception

Stop showing error from HTTP or DIO request

I have a problem when I get an error request from API (when server response 500).
I am using dio or http plugin for flutter plug in.
The problem is that flutter does not show any error.
(DIO: resp.data, HTTP: resp.body)
try this for exception handling
try {
Response response = await dio.get('https://google.com');
print(response.statusCode); // 500
print(response.data); // Contains a Dio Error object
} on DioError catch(e) {
print(e);
}
}
You will retrieve in any case a Response object. According to the DIO Handling Errors documentation, it will return a DioError Object.
// DIO Example
Response response = await dio.get('https://google.com');
print(response.statusCode); // 500
print(response.data); // Contains a Dio Error object
The HTTP package works similarly.
var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print(response.statusCode); // 500
print(response.body); // Error message
This means in any case you are not receiving directly an error for Flutter, you have to handle the error yourself. For example, you could throw an error, if the status code is not 200.
if(response.statusCode == 200){
// everything works as expected
} else {
throw Error();
}

I/flutter (23942): DioError [DioErrorType.RESPONSE]: Http status error [500]

I'm facing HTTP error 500 while Authenticating or log in with API.
and Unable to get this error.
it was working nicely before but suddenly throwing me this HTTP error.
CODE:
The instance of Dio class:
dio() {
Dio dio = Dio();
dio.options.connectTimeout = 60000; //5s
dio.options.receiveTimeout = 60000;
return dio;
}
authenticating method:
Future<Map> authenticate({#required String username, #required String password}) async{
String url = "https://.....";
Response response;
try{
response =await dio().post(
url,
options: Options(
contentType: ContentType.parse("application/x-www-form-urlencoded"),
),
data: {
'grant_type': 'password',
'client_id':clientId,
'client_secret':clientSecret,
'username': username,
'password': password,
}
);
print("Authentication post response.dataaaaaa:${response.data}");
return response.data;
}catch(e){
print("ERROR:$e");
throw e;
}
}
Getting error in catch bloc:
DioError [DioErrorType.RESPONSE]: Http status error [500]
Http status code 500 means something wrong from your API backend?