Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

flutter

dart

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.

like image 917
Steven Rothenburger Avatar asked Dec 18 '22 15:12

Steven Rothenburger


1 Answers

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.

like image 57
Steven Rothenburger Avatar answered Jan 05 '23 14:01

Steven Rothenburger