首页 > 解决方案 > Flutter http.post 抛出 405 需要 POST 方法

问题描述

我正在尝试使用颤振登录 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

错误状态

请问,我该如何处理?

编辑:

这似乎有效:

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

看起来服务器无法识别我的请求的“正文”。

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

解决方案


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

推荐阅读