【问题标题】:Flutter http.post throw 405 requires POST methodFlutter http.post 抛出 405 需要 POST 方法
【发布时间】:2021-06-16 20:38:37
【问题描述】:

我正在尝试使用 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, url, queries),
  body: jsonEncode(formMap),
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  encoding: Encoding.getByName("utf-8"),
);
  • 状态码 200
  • 响应正文 = {"stat":"fail","err":1002,"message":"缺少参数:用户名"}

服务器似乎无法识别我的请求的“正文”。

【问题讨论】:

  • Uri.https('remiFlutter.piwigo.com', 'ws.php', queries), 我认为你的错误在这里
  • 这是我用于 GET 请求的相同格式,它似乎与来自flutter.dev/docs/cookbook/networking/send-dataUri.https('jsonplaceholder.typicode.com', 'albums'), 非常相似
  • 就这样试试吧。 var result = await http.post(Uri.parse('remiFlutter.piwigo.com', headers: &lt;String, String&gt;{'Content-Type': 'application/json; charset=UTF-8'}, body: jsonEncode(&lt;String, String&gt;{'username': myUsername,'password': myPassword}))
  • the named parameter 'headers' isn't defined,同样适用于正文。我可能有另一个版本的飞镖。

标签: flutter http-status-code-405 flutter-http


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2016-05-05
    • 2014-01-24
    • 2017-01-27
    • 2013-06-24
    • 2015-03-08
    相关资源
    最近更新 更多