【问题标题】:400 BAD Request while http.post() in flutter400 BAD Request while http.post() in flutter
【发布时间】:2021-09-26 15:51:29
【问题描述】:

我创建了 heroku 网络应用程序,它接受 districtseasonmin_tempmax_temp 作为 POST 请求中的 bodyParms,它返回一个带有单个对象 crop 的 JSON。

网址

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

POSTMAN 完全可以正常工作,您可以使用x-www-form-urlencoded 来检查正文参数

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

crop: Dry Chillies 作为输出


如果我在颤振中尝试这些步骤。我收到400 BAD Request ERROR

代码

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

错误

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>

注意:即使尝试了导致相同错误的 http 和 dio 包。

【问题讨论】:

    标签: flutter post postman http-status-code-400


    【解决方案1】:

    我花了将近一天的时间来解决一个类似的问题,并通过编写硬编码的 http 标头解决了这个问题。

    试试这个

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

    改为

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

    这个解决方案也可以应用到 Dio。

    【讨论】:

      【解决方案2】:

      尝试将您的请求正文包含在 jsonEncode 方法中。而不是将您的 JSON 字符串直接放在 request.write('Your JSON String') 中。使用request.write(jsonEncode(Your JSON as a MAP object))

      【讨论】:

      • 也试过这个问题:(
      • 好的。 stackoverflow.com/questions/59696140/… 试试这个。它没有帮助我。即使我在使用 HTTPClient 时也遇到了这个错误。但是在使用 http 包之后,我不再得到这个了。
      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多