I can't make simple POST request with header 'content-type' : 'application/json'. With some investigation, i figure out this source code
else if (contentType.mimeType != "application/x-www-form-urlencoded") {
throw new StateError('Cannot set the body fields of a Request with '
'content-type "${contentType.mimeType}".');
}
and comment out that. But not work at all, this lib calculate wrong my 'content-length' header, when i send request from Postman, content-length is 80 but when send use this lib content-length is only 69. My API back-end was pre-build, i can't change how they accept content-type value (currently API accept only 'application/json'). I spend fews hours for a simple POST request, but not work at all. How can I solve this problem? I don't think set some strict rules is a good idea for design a library. Thanks.
@HaiVu5583 I'm guessing that you're trying to pass a Map as the body. In this case it would assume that you are actually doing a application/x-www-form-urlencoded. What you need to do is encode the Map as a string and then do what you're doing.
@donny-dont is correct, the exception is caused by incorrectly setting bodyFields.
See: https://pub.dartlang.org/documentation/http/latest/http/Request/bodyFields.html
bodyFields is for form-encoded data, not JSON.
For an example of how to POST JSON see:
https://www.dartlang.org/tutorials/dart-vm/httpserver#making-a-post-request-from-a-standalone-client
Thanks you all. I misunderstood. That work now.
Most helpful comment
@HaiVu5583 I'm guessing that you're trying to pass a Map as the body. In this case it would assume that you are actually doing a
application/x-www-form-urlencoded. What you need to do is encode the Map as a string and then do what you're doing.