Http Post Unhandled Exception: Invalid argument(s): Invalid request body "Instance of 'Class'' - flutter-http

I have a post function that posts a object to server. But I get this error: Unhandled Exception: Invalid argument(s): Invalid request body "Instance of 'UserModel'"
Future<void> login(UserModel loginUser) async {
String apiUrl = Constants.apiUrl + '/api/auth/login';
http.Response response = await http.post(Uri.parse(apiUrl),
headers: {'Content-Type': 'applicataion/json'}, body: loginUser);
}
What is my mistake?

Related

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

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.

http-mock-adapter Dio Assertion failed: "Could not find mocked route matching request for

I'm trying to mock my Dio client with http-mock-adapter on put method and error method but I get this errors:
Exception: Assertion failed: "Could not find mocked route matching request for POST /onboard/answer { data: {"pageId":"1"},
Exception: DioError [DioErrorType.response]: {message: Some beautiful error!}
I found this issue https://githubmemory.com/repo/lomsa-dev/http-mock-adapter/issues/96?page=2 but I didn't solve my problem. Below is the code
main() {
final dio = Dio(BaseOptions());
final dioAdapter = DioAdapter(dio: dio);
dio.httpClientAdapter = dioAdapter;
final service = NetworkService(dio);
test("should return a DioError", () async {
const path = "/onboard/page-date/0/lastAnswerId";
final dioError = DioError(
error: {'message': 'Some beautiful error!'},
requestOptions: RequestOptions(path: path),
response: Response(
statusCode: 404,
requestOptions: RequestOptions(path: path),
),
type: DioErrorType.response,
);
dioAdapter.onGet(path, (server) {
server.throws(404, dioError);
});
final result = await service.getOnboardingAnswer("lastAnswerId");
expect(result, isA<OnboardModel>());
});
final answerModel = AnswerModel(pageId: "1");
test("should return 200", () async {
const path = "/onboard/answer";
dioAdapter.onPost(path, (server) {
server.reply(200, 200);
});
final result = await service.postOnboardingAnswer(answerModel);
expect(result, isA<int>());
});
instead of final dioAdapter = DioAdapter(dio: dio);
use final dioAdapter = DioAdapter(dio: dio, matcher: const UrlRequestMatcher()); this line only match passed URL not entire http request, so it should work on your case
in this example from official lib your default adapter using FullHttpRequestMatcher which means that it will match your entire request including passed POST parameter
I had the same issue. Dio fails because it tries to match route with the exact data payload you are sending.
If you don't care about the actual data being sent you can use Matchers.any from http-mock-adapter lib:
dioAdapter.onPost(url, (server) {
server.reply(200, 200);
}, data: Matchers.any);

Flutter: I try to get api from backend with authorization bearer token in header using dio pack and http , i got Exception but is working in postman

This is my code
Future<List<ContentHome>>getContentHome()async{
final response = await http.get(
Uri.parse('http://IPServerBackend/api/content/getAllContentHome/2?pgsize=10&pgnum=1'),
// Send authorization headers to the backend.
headers: {
"Accept": 'application/json',,
"Content-Type" : "application/json",
"Authorization": "Bearer MyToken",
},
);
final responseJson = jsonDecode(response.body);
return (responseJson as List).map(
(e) => ContentHome.fromJson(e),
).toList();
}
The Exception:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected
How to solve this?

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?

Dart unable to parse JSON from string to int

I am trying to parse a JSON value from string to int but got stuck :(
The code below shows a HTTP get request and retrieving a JSON object in which I want to obtain the 'reps' value in Integer.
var response = await httpClient.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'X-API-Key': apikey
});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
var res = json.decode(response.body);
String repStr = res['reps'];
print(repStr);
int repInt = int.parse(repStr);
The debug console shows the following error on the line
String repStr = res['reps'];
E/flutter ( 8562): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'int' is not a subtype of type 'String'
As the exception explains, the value res['reps'] is already an integer you don't need to parse it.
int repStr = res['reps'];