Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

flutter

dart

Map<String,String> headers = {'Content-Type':'application/json','authorization':'Basic c3R1ZHlkb3RlOnN0dWR5ZG90ZTEyMw=='};  var response = await post(Urls.getToken,         headers: headers,         body: {"grant_type":"password","username":"******","password":"*****","scope":"offline_access"},       );  

When I execute this I am unable to recieve data and the error thrown is

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

like image 323
Fayaz Avatar asked Feb 24 '19 07:02

Fayaz


2 Answers

You need to wrap the body in jsonEncode.

import 'package:http/http.dart' as http; import 'dart:convert';  Map<String,String> headers = {'Content-Type':'application/json','authorization':'Basic c3R1ZHlkb3RlOnN0dWR5ZG90ZTEyMw=='}; final msg = jsonEncode({"grant_type":"password","username":"******","password":"*****","scope":"offline_access"});  var response = await post(Urls.getToken,                headers: headers,                body: msg,             ); 
like image 150
Monza Avatar answered Sep 17 '22 09:09

Monza


Use jsonEncode to wrap your body object.

import 'package:http/http.dart' as http; import 'dart:convert';  var headers = {     'Content-Type':'application/json',     'authorization':'Basic c3R1ZHlkb3RlOnN0dWR5ZG90ZTEyMw==' };  final body = {     'username':'foo',     'password':'pass123' }  var response = await post(     Urls.getToken,     headers: headers,     body: jsonEncode(body), // use jsonEncode() ); 

Why jsonEncode?

body: It can be a HTML, JSON or XML, etc. This mean is we need to send/recive data in that perticular format. You can set this in content-type header its default value is text/plain.

As you set the content-type header to JSON you must have to pass a "valid" JSON as the body. But you are passing Map<String, String> as the body, which obviously throws an error.

So to solve this issue you need to change (or encode) your Map<String, String> data to JSON data.

Best way to do this is to use jsonEncode function.

like image 40
Rohit Nishad Avatar answered Sep 19 '22 09:09

Rohit Nishad