【问题标题】:why flutter often occur return connection closed before full header was received为什么在收到完整标头之前经常发生颤动返回连接关闭
【发布时间】:2022-08-15 04:49:10
【问题描述】:

我使用HTTP 连接到API,我尝试了一些类似2.5, 2.10.5, 3 的flutter sdk,但仍然经常出现同样的问题,返回connection closed before full header was received。它可能发生在随机 api 和我构建的所有应用程序中。

它是我的代码示例

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

    标签: flutter


    【解决方案1】:

    有一个issue ongoing on the Flutter repo 描述了您的问题。

    给定的解决方法之一是使用HttpClient 并将allowLegacyUnsafeRenegotiation 属性设置为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'));
    }
    

    此解决方案仅适用于移动设备,http 包不应在 Web 模式下使用。

    【讨论】:

    【解决方案2】:

    我通过使用 HTTP (More info) 包的 send() 方法解决了这个问题

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      相关资源
      最近更新 更多