Jitendra Mistry
Jitendra Mistry

Reputation: 407

Flutter POST request body is empty on server side

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;
  }

Upvotes: 3

Views: 1401

Answers (2)

num8er
num8er

Reputation: 19372

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;
}

Upvotes: 2

Sukhi
Sukhi

Reputation: 14145

The output you see looks more of a Map than the JSON string. You might want to try setting up the hard-coded data first just to check everything is okay from the server end.

Map<String, dynamic> data = {
    "coach_id":id,
    "date":_value ,
    "user_id":userId ,
    "timeslots":duration
  };


HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

request.headers.set('Accept', 'application/json');
request.headers.set('Content-type', 'application/json');
request.add(utf8.encode(json.encode(data))); 
// utf8 is optional but a good idea so as to handle the different chars

HttpClientResponse response = await request.close();

String serverResponse = await utf8.decoder.bind(response).join();
print(serverResponse);

Upvotes: 0

Related Questions