why flutter often occur return connection closed before full header was received

Viewed 98

I use HTTP for connection to API, and I have tried some flutter sdk like 2.5, 2.10.5, 3 but still have same issue often occur return connection closed before full header was received. and it's can occur in random api and all apps I build in flutter.

it's example of my code

Future<dynamic> getGoodSolution() async {
    final url = Uri.parse('$url');
    final headers = {HttpHeaders.contentTypeHeader: 'application/json', HttpHeaders.authorizationHeader: 'Bearer mytoken123'};
    var map = <String, dynamic>{};
    map["xxx"] = "123";
    // print(headers);

    try {
      final response = await client.post(url, headers: headers, body: json.encode(map));
      final data = xxxFromJson(response.body);
      return data;
    } catch (e) {
      print(e);
      return null;
    }
  }
2 Answers

I solved the problem by using the send() method of the HTTP (More info) package

Future<dynamic> getGoodSolution() async {
  final url = Uri.parse('$url');
  final headers = {HttpHeaders.contentTypeHeader: 'application/json',HttpHeaders.authorizationHeader: 'Bearer mytoken123'};
  var map = <String, dynamic>{};
  map["xxx"] = "123";

  try {
    var request = http.Request('POST', url);

    request.headers.addAll(headers);
    request.body = json.encode(map);

    var streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);

    final data = xxxFromJson(response.body);
    return data;
  } catch (e) {
    print(e);
    return null;
  }
}

There is an issue ongoing on the Flutter repo which describes your problem.

One of the given workarounds is to use a HttpClient and to set the allowLegacyUnsafeRenegotiation property to true

void main() async {
  final context = SecurityContext.defaultContext;
  context.allowLegacyUnsafeRenegotiation = true;
  final httpClient = HttpClient(context: context);
  final client = IOClient(httpClient);

  await client.get(Uri.parse('https://your_uri.net'));
}

This solution will only work on mobile though, the http package should not be used in Web mode.

Related