Flutter:接收数据时连接已关闭

时间:2020-07-23 18:49:57

标签: api http flutter dart httpexception

我正在调用post API,有时我会从服务器获取响应,有时会收到异常Connection closed while receiving data。在两种情况下,请求都是相同的,并且根据后端服务器日志,发送了响应,但我没有收到。 我在模拟器和实际设备中都遇到了这个问题。

try {
  final result =
      await http.post(url, body: encodedBody, headers: apiHeader);
  Map<String, dynamic> response = json.decode(result.body);

  print("Response: $response");

  return response;
} catch (error) {
  Map<String, dynamic> response = Map<String, dynamic>();
  response['success'] = false;
  response['message'] = error;
  return response;
}

3 个答案:

答案 0 :(得分:1)

您的请求标头中的

Keep-Alive标头可能会丢失,请检查API必需的标头

答案 1 :(得分:0)

这取决于您要调用的服务器或Rest API。

有时候,要仔细检查您使用的是有效且适当的URL端点。

另一种可能性是它没有在标题处正确接收身份验证。我曾经遇到过一个问题,它可以解决通过URL作为端点进行身份验证的问题。尝试研究服务器或rest api是否支持其他身份验证选项(如最后一个提到的那样)。

答案 2 :(得分:0)

我遇到了有关get请求的问题,有时我从服务器获得响应,有时在同一按钮单击事件上收到异常Connection closed while receiving data。然后我发现数据库中特定表的记录数量很大。我建议的解决方案是在pagination中使用backend server