vishnuvreddy
vishnuvreddy

Reputation: 23

400 BAD Request while http.post() in flutter

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.

Upvotes: 2

Views: 7321

Answers (2)

onrgns
onrgns

Reputation: 61

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.

Upvotes: 1

Mohanakrrishna
Mohanakrrishna

Reputation: 168

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

Upvotes: 0

Related Questions