Search code examples
apiflutterhttpflutter-web

PostMan is working but http is giving 404 error in flutter


I am using following code for my api. This api is working in postman but showing 404 error code in http flutter.

My flutter code:

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

It is giving error code 404 .

Following is postman result:

Post Man result


Solution

  • You are setting the wrong headers. The Accept header is for determining which result type you expect from the server. From your screenshot (and the data) it seems quite clear, you would expect an image/jpg. On the other hand, you are missing the Content-Type header, which defines what type of data you are sending with your request, in your case application/json. So the server probably can't parse the body correctly.

    Assuming, that jsonEncode is just something like JSON.stringify you should do something like the following

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