Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter POST request body is empty on server side

Tags:

flutter

dart

var post = jsonEncode({
    "coach_id":id,
    "date":_value ,
    "user_id":userId ,
    "timeslots":duration ,
});

print(post);

var response = await http.post(url,headers:{"Content-Type":"application/json"}, body: post);


if (response.statusCode == 200) {


var responseJson = json.decode(response.body);
print(responseJson);

  return response;
} else {
  return null;
}
  } catch (exception) {

    print('exception---- $exception');
    return null;
  }
like image 443
Jitendra Mistry Avatar asked Nov 22 '25 15:11

Jitendra Mistry


1 Answers

So I've done request using postman and understood that server accepts: application/x-www-form-urlencoded content type.

So correct way doing postman request is:

1

and correct code is:

import 'package:http/http.dart' as http;
import 'dart:convert';
try {
  final headers = {
    "Accept": "application/json",
    "Content-Type": "application/x-www-form-urlencoded"
  };

  final form = [];
  form.add("coach_id=$id");
  form.add("date=$_value");
  form.add("user_id=$userId");
  for (var value in duration) {
    form.add("timeslots[]=$value");
  }
  final body = form.join('&');

  final response = await http.post(url, headers: headers, body: body);

  if (response.statusCode == 200) {
    return json.decode(response.body);
  }
  return null;
}
catch (exception) {
  print(exception.error);
  return null;
}
like image 120
num8er Avatar answered Nov 24 '25 23:11

num8er



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!