Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter HTTP Post returns 415

Tags:

flutter

dart

I have an issue with using Method.Post on my flutter app using http dart library. It seems that when I tried to post data from my WebAPI it gaves me a StatusCode 415. See my code below:

Code Login:

Future<User> login(User user) async {
print(URLRequest.URL_LOGIN);
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: {
  'username': user.username,
  'password': user.password
}, headers: {
  "Accept": "application/json",
}).then((dynamic res) {
  print(res.toString());
});
}

Code NetworkUtils:

Future<dynamic> post(String url, {Map headers, body, encoding}) async {
return await http
    .post(url, body: body, headers: headers, encoding: encoding)
    .then((http.Response response) {
  final String res = response.body;
  final int statusCode = response.statusCode;

  if (statusCode < 200 || statusCode > 400 || json == null) {
    throw new Exception('Error while fetching data.');
  }

  return _decoder.convert(res);
});
}

Does anyone knew whats going on my code?

like image 759
Alvin Quezon Avatar asked Oct 01 '18 03:10

Alvin Quezon


1 Answers

Try adding this new header:

headers: {
  "Accept": "application/json",
  "content-type":"application/json"
}

UPDATE

Ok now you need to send json data, like this :

        import 'dart:convert';


         var body = jsonEncode( {
          'username': user.username,
          'password': user.password
        });


        return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: body, headers: {
          "Accept": "application/json",
          "content-type": "application/json"
        }).then((dynamic res) {
          print(res.toString());
        });
        }
like image 162
diegoveloper Avatar answered Oct 19 '22 17:10

diegoveloper