Flutter http.post throw 405 需要 POST 方法

问题描述

我正在尝试使用 Flutter 登录 API。 方法如下:

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,}),);

带有 405 错误的请求结果说:

This method requires HTTP POST

error status

请问,我该如何处理?

编辑:

这似乎有效:

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


http.Response response = await http.post(
  Uri.https(host,body: jsonEncode(formMap),headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },encoding: Encoding.getByName("utf-8"),);
  • 状态代码 200
  • 响应正文 = {"stat":"fail","err":1002,"message":"缺少参数:用户名"}

看起来我的请求的“正文”没有被服务器识别。

解决方法

我真的不知道为什么,但它与 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()}");