http - HTTP 请求未在响应中执行 - Flutter/Dart

标签 http flutter dart

我正在尝试对用 C# (.NET Core) 编写的 Web API 执行请求。端点运行异步函数并返回包含操作结果的 JSON。

在 Dart 中我无法得到响应。 then()catchError() 只是不执行。

端点获取负载中的产品。当我只发送一个产品时我可以得到响应,但是当我发送两个或更多时我不能。

有效载荷是:

http .post('http://192.168.0.10:5000/api/v1/oficina/dart',
                  body: jsonEncode({
                    "usuario": "edigleyssonsilva",
                    "senha": "123456",
                    "codEmp": 1,
                    "codFil": 1,
                    "produtos": [
                      {
                        "ccuRes": "160",
                        "codEmp": 1,
                        "codFil": 1,
                        "codPro": "570.0001",
                        "codTns": "90250",
                        "datPrv": "2020-02-17",
                        "datEme": "2020-02-17",
                        "qtdEme": 2
                      }
                    ]
                  }),
                  headers: {'Content-Type': 'application/json'})
              .then((value) => print(value.body))
              .catchError((err) {
                print('Ocorreu um erro');
                print(err);
              });

我已经在 Postman、Angular 应用程序和用 Dart 编写的测试文件上用相同的负载测试了相同的端点,这非常有效。

所以,我不知道为什么它在 Flutter 中不起作用

最佳答案

你分享的代码不是很清楚,要么也分享调用这个函数的代码,但你也可以尝试,将你的 body 分配给一个Map对象,然后用json.encode编码,因为jsonEncode是在新版本中已弃用,尽管它可以工作,但您应该使用新的方式对其进行编码。 此外,您应该在执行任何异步工作时使用 async-await。

Future<void> request() async {

 Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
Map body = {"usuario": "edigleyssonsilva",
                    "senha": "123456",
                    "codEmp": 1,
                    "codFil": 1,
                    "produtos": [
                      {
                        "ccuRes": "160",
                        "codEmp": 1,
                        "codFil": 1,
                        "codPro": "570.0001",
                        "codTns": "90250",
                        "datPrv": "2020-02-17",
                        "datEme": "2020-02-17",
                        "qtdEme": 2
                      }
                    ]};
final response = await http.post(url, 
                body: json.encode(body), 
                headers: headers,
              ).catchError((err) {
                print('Ocorreu um erro');
                print(err);
              });
print('Response: ${response.body}');
}

关于http - HTTP 请求未在响应中执行 - Flutter/Dart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60279228/

相关文章:

http - 使用 HTTPS 时 OAuth 是否无关紧要?

flutter - 预编译build_runner失败:build_runner:

dart - 调用构造函数 super 错误,传递了 3 个,预期为 0 个

types - 是否可以在静态方法中获取类类型?

C套接字仅使用二进制数据造成内存泄漏

java - 在 android 上具有授权的 HTTP POST 请求

flutter - 如何更改底部导航栏的颜色?

flutter - 断言失败 : boolean expression must not be null exception

asynchronous - 我怎样才能正确地从使用 Futures/async/await 的流中产生?

http - 如何在不使用 golang 中的 ioutil.ReadAll 的情况下检索网站源