Reputation: 233
I'm calling post API, and sometimes I get the response from the server and sometimes I receive the exception:
Connection closed while receiving data.
Request is same in both cases, and according to backend server logs, a response is sent but I didn't receive it. I have this issue both in simulator and actual device.
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;
}
Upvotes: 23
Views: 31702
Reputation: 484
In my case the server was closing the connection when there was no 'Accept-Encoding'
header, even with 'Connection': 'Keep-Alive'
. The backend was developed in Laravel, but I don't have much information. I added to the header 'Accept-Encoding': 'gzip, deflate, br'
and it worked as it should. Don't ask me for an explanation, because I don't have it
Upvotes: 4
Reputation: 649
I have resolved this, by using this GitHub issue https://github.com/flutter/flutter/issues/22951
Upvotes: 1
Reputation: 153
I had the issue with a get request, sometimes I get the response from the server and sometimes I receive the exception Connection closed while receiving data
on same button click event. Then I founded that the number of records of particular table in database is quite large. My suggested solution is to use pagination
in the backend server
.
Upvotes: 4
Reputation: 3305
Keep-Alive
header in the headers of your request might be missing, please check with APIs required headers
Upvotes: 13
Reputation: 11
It depends on the server or Rest API you are trying to call.
Sometimes it is a matter of double checking you are using a valid and appropriate URL endpoint.
Another possibility is that it is not correctly receiving authentication at the header. I had that problem once and it got solved authenticating trough the url as endpoints. Try researching if the server or rest api supports other authentication options as this last one mentioned.
Upvotes: 1