【问题标题】:Flutter - ERROR : HTTP 405 Method not allowedFlutter - 错误:不允许使用 HTTP 405 方法
【发布时间】:2020-02-13 05:34:35
【问题描述】:

我正在尝试通过客户端提供给我的 API 读取 json 文件,但它给出了 HTTP 错误 405 说方法不允许。谁能告诉我做错了什么?

这个 api 请求 sn-p 给了我:

curl 'http://finelistings.com/backend/apis/webbrands/' -H 'Content-Type: application/json' -H 'Accept: application/json' --data-binary '{}' --compressed --insecure
Future<String> getData() async {
    var response = await http.get(
      Uri.encodeFull("http://finelistings.com/backend/apis/webbrands/"),
      headers: {
        "Accept": "application/json",
      }
    );

    Map<String, String> data = jsonDecode(response.body);

    print(data);
  }

【问题讨论】:

  • Curl 调用是否正常工作?
  • 有一个 great resource 可以将 curl 命令转换为 dart。正如@Torkel 所注意到的,您需要作为 POST 提交。您错过了 curl 命令的部分内容,即 --data-binary...,该部分 向服务器发送正文,该请求必须通过 POST 完成。

标签: json api http flutter dart


【解决方案1】:

Method not allowed 可能是指错误的请求方法。

尝试使用 POST 而不是 GET,至少我使用提到的 URL 得到了响应。

Future<String> getData() async {
    var response = await http.post(
      Uri.encodeFull("http://finelistings.com/backend/apis/webbrands/"),
      headers: {
        "Accept": "application/json",
      }
    );

    Map<String, dynamic> data = jsonDecode(response.body);

    print(data);
  }

【讨论】:

  • 我尝试了这种方法,但现在我在Map&lt;String, String&gt; data = jsonDecode(response.body); 线上遇到了一个新错误。 错误: Exception has occurred. _TypeError (type '_InternalLinkedHashMap&lt;String, dynamic&gt;' is not a subtype of type 'Map&lt;String, String&gt;')
  • 尝试使用动态而不是字符串?这就是错误消息所说的
猜你喜欢
  • 2011-06-21
  • 2014-12-12
  • 2017-10-16
  • 2016-03-08
  • 2016-08-24
  • 2018-01-07
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多