Home > OS >  POST Http request problem with passing arguments
POST Http request problem with passing arguments

Time:10-31

I'm trying to send to server with a POST http request a list with three arguments. The response status is 200 but when I print the response body is null and it keeps printing it in a loop. I can't figure out what I'm doing wrong. Any help will be much appreciated!

POST request

 static Future<Athlete> insertPresences(
      int athleteId, int departmentId, int teamId) async {
    var body = [
      {"athleteId": athleteId, "departmentId": departmentId, "teamId": teamId}
    ];
    try {
      final response =
          await http.post(Uri.parse('$uri/nox/api/insert-presences'),
              headers: <String, String>{
                'Authorization': 'Basic a2F4cmlzOjEyMzQ1',
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept': 'application/json'
              },
              body: json.encode(body),
             );
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');

      if (response.statusCode == 200) {
        if (response.body.isNotEmpty) {
          return Athlete.fromJson(jsonDecode(response.body));
        }
      }
    } catch (e) {
      print(e);
    }
    return insertPresences(athleteId, departmentId, teamId);
  }

Postman raw body

[ 
     { 
    "athleteId":"16198",
    "departmentId":"3",
    "teamId":"278"
  }
]

What it prints

flutter: Response status: 200
flutter: Response body:
flutter: Response status: 200
flutter: Response body:
flutter: Response status: 200
flutter: Response body:

and it keeps going until I stop it

CodePudding user response:

Your response body is null, so it does not jump in your if

if (response.body.isNotEmpty) {
          return Athlete.fromJson(jsonDecode(response.body)); // NOT CALLED
}

But the last return is executed, this creates a loop, because you call the insertPresences method again in the return.

  • Related