I'm struggling with http post in order to get some data from an API, but the response.body is always empty. Testing on https://reqbin.com/ works fine, so the problem is inside the code.
try {
final response = await http.post(
Uri.parse(
'https://webservicesp.anaf.ro/PlatitorTvaRest/api/v8/ws/tva'),
headers: <String, String>{
"Access-Control-Allow-Origin":
"*", // Required for CORS support to work
"Access-Control-Allow-Credentials":
'true', // Required for cookies, authorization headers with HTTPS
"Access-Control-Allow-Headers":
"Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Methods": "GET,POST,HEAD,DELETE",
"Cache-Control": "no-cache",
'Content-Type': 'application/json'
},
body: jsonEncode({
'cui': _identificationController.text.trim(),
'data': DateFormat('yyyy-MM-dd').format(DateTime.now())
}),
);
if (response.statusCode == 200) {
// If the server responds successfully
// then parse the JSON.
print(response.body.length);
if(response.body.isNotEmpty)
{
final responseData = jsonDecode(response.body);
print(responseData);
}
else
{
print("Response body is empty\n");
}
} else {
// If the server did not return a 200 CREATED response,
// then throw an exception.
throw Exception(
'Failed to fetch company data from ANAF: ${response.statusCode}');
}
} catch (e) {
print(e);
}
While executing I've got two scenarios:
Also I had to disable web security in chrome.dart file in order to be able to execute the http.post
. Any idea how can I configure the CORS?
The body of the POST must be a JSON array, even if there is one JSON object.
The following code (with the outermost []
s) works. If you remove the []
it fails.
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
final response = await http.post(
Uri.parse('https://webservicesp.anaf.ro/PlatitorTvaRest/api/v8/ws/tva'),
headers: {'content-type': 'application/json'},
body: json.encode(
[
{'cui': 1234, 'data': '2015-02-14'}
],
),
);
print(response.body);
}