Reputation: 2690
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?
Upvotes: 6
Views: 13780
Reputation: 5207
There are several things to keep in mind.
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.
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".
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:
Upvotes: 3