PostMan 正在工作,但 http 在 flutter 中给出 404 错误

PostMan is working but http is giving 404 error in flutter

我正在为我的 api 使用以下代码。这个 api 在邮递员中工作,但在 http flutter 中显示 404 错误代码。

我的flutter代码:

 RaisedButton(
          onPressed: () {
            apiCall();
          },
          child: Text("Press"),
        )

  Future apiCall() async {
    var body =
        jsonEncode({"filepath": "patient/reports/1602333458533-Liver.jpg"});
    try {
      await http
          .post('http://3.6.197.52:3100/downloadFile',
              headers: {"Accept": "Application/json"}, body: body)
          .then((http.Response response) => print(response.statusCode));
    } catch (e) {
      print(e);
    }
  }

它给出了错误代码 404。

邮递结果如下:

Post Man result

您设置的 header 有误。 Accept header 用于确定您期望从服务器获得的结果类型。从您的屏幕截图(和数据)看来很清楚,您会期望 image/jpg。另一方面,您缺少 Content-Type header,它定义了您随请求发送的数据类型,在您的情况下为 application/json。所以服务器可能无法正确解析 body。

假设 jsonEncode 就像 JSON.stringify 你应该做类似下面的事情

Future apiCall() async {
    var body =
        jsonEncode({"filepath": "patient/reports/1602333458533-Liver.jpg"});
    try {
      await http
          .post('http://3.6.197.52:3100/downloadFile',
              headers: {"Content-Type": "application/json"}, body: body)
          .then((http.Response response) => print(response.statusCode));
    } catch (e) {
      print(e);
    }
  }