2

I am created heroku web app which accepts district, season, min_temp, max_temp as bodyParms in POST request which returns a JSON with single object crop.

URL

https://agrocare-api.herokuapp.com/predictCrop

It works completely fine with POSTMAN, You can check with body params with x-www-form-urlencoded

district: DAVANGERE
min_temp: 20
max_temp: 21
season: kharif

which gives crop: Dry Chillies as output


If I try these steps in flutter. I am getting 400 BAD Request ERROR

Code

Future callApi(String district, String season, String minTemp, String maxTemp) async {

  Uri url = Uri.parse('https://agrocare-api.herokuapp.com/predictCrop');

  final client = HttpClient();
  final request = await client.postUrl(url);
  request.headers.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
  request.write('{"district": $district,"season": $season, "min_temp": $minTemp, "max_temp": $maxTemp}');
  final response = await request.close();
  response.transform(utf8.decoder).listen((contents) {
    print(contents);
  });
  return response;
}

Error

I/flutter ( 6462): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
I/flutter ( 6462): <title>400 Bad Request</title>
I/flutter ( 6462): <h1>Bad Request</h1>
I/flutter ( 6462): <p>The browser (or proxy) sent a request that this server could not understand.</p>

Note: Even tried http and dio packages which result same error.

vishnuvreddy
  • 23
  • 1
  • 4

2 Answers2

1

I spent almost a day for a similar problem and solved the problem by writing hardcoded http headers.

try this

request.headers.set("Content-Type", "application/json; charset=UTF-8");

instead

request.headers.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");

This solution can also be applied to Dio.

onrgns
  • 61
  • 4
0

Try to have your request body in an jsonEncode method. Instead of putting ur JSON String directly in request.write('Your JSON String'). Use request.write(jsonEncode(Your JSON as a MAP object))

Mohanakrrishna
  • 148
  • 3
  • 13
  • Tried this too same problem :( – vishnuvreddy Jul 18 '21 at 21:07
  • Ok. https://stackoverflow.com/questions/59696140/http-post-works-in-postman-but-not-in-flutter Try this. It did not help me. Even I was getting this error when I used HTTPClient. But after using http package, I am not getting this anymore. – Mohanakrrishna Jul 19 '21 at 03:44