Send JSON body with HTTP get request

家住魔仙堡 提交于 2021-01-27 07:47:52

问题


I'm trying to put JSON body query parameters into http.get request. I tried to even follow this Flutter: Send JSON body for Http GET request but no luck there. No matter what I put into params variable I get all results from my backend. I have tested backend with postman and everything works fine

Here is my code in flutter

 Future<List<Country>> fetchCountries(String name) async {
    final token = Provider.of<Auth>(context, listen: false).token;
    final params = {"name": "Uk"};
    try {
      Uri uri = Uri.parse(APIPath.findCountry());
      final newUri = uri.replace(queryParameters: params);
      print(newUri); //prints http://localhost:8080/country/find?name=uk
      final response = await http.get(newUri,
          headers: [APIHeader.authorization(token), APIHeader.json()]
              .reduce(mergeMaps));
      final jsonResponse = json.decode(response.body);
      if (response.statusCode == 200) {
        Iterable list = jsonResponse['result'];
        print(list);
        return list.map((model) => Country.fromJson(model)).toList();
      } else {
        throw HttpException(jsonResponse["error"]);
      }
    } catch (error) {
      throw error;
    }
  }

Placing body into http.get request doesn't work as for http.post request. Any idea what am I doing wrong?


回答1:


There are several things to keep in mind.

1) The HTTP RFC for method GET says:

A payload within a GET request message has no defined semantics...

It is a bad architectural style, to send any data in the body of GET request.

2) If you want to ignore that and still want to send body in the GET request, it makes sense to set content type header to "application/json".

3) The example you referred does not use body in the GET request. Instead, it retrieves parameter values from the given JSON object and puts them to a URL. Then this URL is called via GET without body.

My suggestion:

  • If the number of URL parameters is relatively small and their values are short, so that the resulting URL is readable, use GET and URL with parameters.
  • If the URL with parameters becomes hard to read, put parameters to the body and use POST.
  • There are no precise criteria. It is a matter of your taste and your personal preferences. The readability of URL may be just one of criteria to consider when choosing GET or POST.


来源:https://stackoverflow.com/questions/62376667/send-json-body-with-http-get-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!