send json body http get flutter
To send a JSON body in an HTTP GET request in Flutter, you can use the http
package. However, it's important to note that sending a JSON body in an HTTP GET request is not a common practice and may not be supported by all APIs due to security concerns. GET requests are typically used to retrieve data and should not include a request body.
If you need to send data to the server, it's recommended to use an HTTP POST request instead. POST requests are designed for sending data to the server and can include a request body.
Here's an example of how to send a JSON body in an HTTP POST request using the http
package in Flutter:
import 'dart:convert';
import 'package:http/http.dart' as http;
void sendRequest() async {
var url = Uri.parse('https://example.com/api/endpoint');
var headers = {'Content-Type': 'application/json'};
var body = jsonEncode({'key1': 'value1', 'key2': 'value2'});
var response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 200) {
// Request successful
var responseData = jsonDecode(response.body);
// Process the response data
} else {
// Request failed
print('Request failed with status: ${response.statusCode}');
}
}
In this example, we use the http.post
method to send an HTTP POST request to the specified URL. We set the Content-Type
header to application/json
to indicate that the request body is in JSON format. We also use the jsonEncode
function from the dart:convert
package to convert a Map object into a JSON string.
Please note that the specific implementation may vary depending on the API you are working with. Make sure to refer to the API documentation for the correct endpoint and request format.