Flutter http 帖子,响应正文始终为空

问题描述 投票:0回答:1

我正在努力处理http post以便从API获取一些数据,但response.body始终为空。在 https://reqbin.com/ 上测试工作正常,所以问题出在代码内部。

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

执行时我有两种情况:

  1. 响应代码200,response.body为空
  2. 响应代码 500 - 内部错误

此外,我还必须禁用 chrome.dart 文件中的网络安全才能执行

http.post
。知道如何配置 CORS 吗?

flutter dart post cors
1个回答
0
投票

POST 的正文必须是一个 JSON 数组,即使有一个 JSON 对象。

以下代码(带有最外面的

[]
)有效。如果删除
[]
,则会失败。

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.