0

I am trying to log into an API with flutter. Here is the method:

var result = await http.post(
  Uri.https(host, url, queries),
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
  body: jsonEncode(<String, String>{
    'username': myUsername,
    'password': myPassword,
  }),
);

The request result with a 405 error saying:

This method requires HTTP POST

error status

Please, how do I deal with that ?

Edit:

This seems to work:

Map<String, String> formMap = {
  'username': 'myUsername',
  'password': 'myPassword',
};


http.Response response = await http.post(
  Uri.https(host, url, queries),
  body: jsonEncode(formMap),
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  encoding: Encoding.getByName("utf-8"),
);
  • Status code 200
  • Response body = {"stat":"fail","err":1002,"message":"Missing parameters: username"}

Looks like the "body" of my request is not recognized by the server.

  • `Uri.https('remiFlutter.piwigo.com', 'ws.php', queries),` I think your mistake here – SefaUn Mar 19 '21 at 12:29
  • This is the same format I am using for GET requests and it seems quite similar to ```Uri.https('jsonplaceholder.typicode.com', 'albums'),``` from https://flutter.dev/docs/cookbook/networking/send-data – Remi Martin Mar 19 '21 at 12:42
  • just try like this. `var result = await http.post(Uri.parse('remiFlutter.piwigo.com', headers: {'Content-Type': 'application/json; charset=UTF-8'}, body: jsonEncode({'username': myUsername,'password': myPassword}))` – SefaUn Mar 19 '21 at 13:39
  • ```the named parameter 'headers' isn't defined```, same for body. I may have another version of dart. – Remi Martin Mar 19 '21 at 13:47

1 Answers1

0

I don't really know why but it worked with a multipartRequest:

var request = http.MultipartRequest('POST', Uri.https(host, url, queries))
  ..fields['username'] = 'myUsername'
  ..fields['password'] = 'myPassword'
  ..headers['Content-Type'] = "application/x-www-form-urlencoded";
var res = await request.send();
print("STATUS CODE = ${res.statusCode}");
print("Response headers = ${res.headers}");
print("Response body = ${res.stream.bytesToString()}");