Http: Bad state: Cannot set the body fields of a Request with content-type "application/json"

Created on 29 May 2018  路  3Comments  路  Source: dart-lang/http

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.

closed-as-intended

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.

All 3 comments

@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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

IrosTheBeggar picture IrosTheBeggar  路  5Comments

Buckstabue picture Buckstabue  路  7Comments

ottomated picture ottomated  路  7Comments

Jonas-Sander picture Jonas-Sander  路  6Comments

Apollo2011 picture Apollo2011  路  8Comments