Steven Rothenburger
Steven Rothenburger

Reputation: 241

How do I set headers on Flutter/Dart http Request object?

I need a way to set the headers of the dart http Request object to application/JSON.

I want to build a Request object to send to my backend API. I set the body to my JSON object, but when it gets sent, it defaults the headers to text/html instead of application/json.

I have tried using the built-in method

http.post(url,dynamic body);

but unfortunately this method places the body in the parameters of the URL and I need it in the actual body of the request.

So instead I built an http Request object, and manually set the URL and body but like I said, it sets the headers to text/html. I have read the docs for https://pub.dev/documentation/http/latest/http/Request-class.html, but unfortunately, I haven't found a way to set the headers.

postRequest(uri) async {

    Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");

    http.Request request = new http.Request("post", url);

    request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';

    var letsGo = await request.send();

    print(letsGo.statusCode);
}


Much thanks for any possible solutions!

Ps. this is my first ask on Stack Overflow so I apologize if I made any errors in posting.

Upvotes: 9

Views: 11447

Answers (2)

s.j
s.j

Reputation: 651

for the post or get any request you can Add Header like this - 

 var permAddUrl =  'your requested url';

 var bodyParameters =  {
      'Email': email,
      'MobileNo': mobileNumber,
    };

   await http.post(
     requesturl,
      headers: {  'Content-Type': 'application/x-www-form-urlencoded',
        "Authorization":"$token",
},

  body: bodyParameters,).then((response) {
      var data = json.encode(response.body);
      print(data);
      setState(() {
        if(response.statusCode == 200){
          //var statesList = data['data'];
          UtilAction.showSnackBar(context, " Details Submitted Successfully");

        }
      });
    });

Upvotes: 4

Steven Rothenburger
Steven Rothenburger

Reputation: 241

Solved!

postRequest(uri) async {

    Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");

    http.Request request = new http.Request("post", url);

    request.headers.clear();
    request.headers.addAll({"content-type":"application/json; charset=utf-8"});
    request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';

    var letsGo = await request.send();

    print(letsGo.statusCode);
}

I was having some issues with the Request object default setting the encoding. By manually specifying utf-8, the server I am contacting accepts it.

Upvotes: 15

Related Questions