You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter http包中Connection reset by peer异常处理方案咨询

处理Flutter http包"Connection reset by peer"异常的方案

1. 立即修复:捕获异常并终止加载状态

应用卡死的核心原因是getRideInfo方法中的网络请求未捕获异步异常,导致进度条一直处于激活状态。直接在请求逻辑外层包裹try-catch-finally即可解决:

Future<void> getRideInfo() async {
  setState(() {
    isLoading = true; // 显示进度条
  });

  try {
    // 你的http请求代码示例
    final response = await http.get(Uri.parse('目标接口地址'));
    // 正常处理响应逻辑
  } catch (e) {
    // 捕获所有网络异常,包括Connection reset by peer
    if (e.toString().contains('Connection reset by peer')) {
      // 针对该异常的用户提示,比如弹出Toast或SnackBar
      print('连接异常,请稍后重试');
    } else {
      print('请求失败: $e');
    }
  } finally {
    // 无论成功/失败,都关闭进度条
    setState(() {
      isLoading = false;
    });
  }
}

2. 进阶优化:封装统一的HTTP客户端

如果应用中有多处网络请求,建议封装全局HTTP服务,统一处理异常,避免重复代码:

import 'package:http/http.dart' as http;
import 'package:http/http.dart';

class HttpHandler {
  final Client _client = http.Client();

  Future<Response> get(String url) async {
    try {
      // 添加超时设置,避免请求无限挂起
      final response = await _client.get(Uri.parse(url))
          .timeout(const Duration(seconds: 12));
      return response;
    } catch (e) {
      if (e.toString().contains('Connection reset by peer')) {
        throw Exception('连接被重置,请检查网络后重试');
      }
      throw Exception('网络请求出错: $e');
    }
  }

  // 可扩展post、put等其他请求方法
}

在页面中使用封装后的服务:

final HttpHandler _httpHandler = HttpHandler();

Future<void> getRideInfo() async {
  setState(() => isLoading = true);
  try {
    final response = await _httpHandler.get('目标接口地址');
    // 处理响应逻辑
  } catch (e) {
    // 统一展示错误提示
    print(e.toString());
  } finally {
    setState(() => isLoading = false);
  }
}

3. 额外体验优化

  • 添加重试机制:针对Connection reset by peer这种偶发异常,可以在捕获后自动重试1-2次:
Future<Response> _getWithRetry(String url, int remainingRetries) async {
  try {
    return await _client.get(Uri.parse(url)).timeout(const Duration(seconds: 10));
  } catch (e) {
    if (remainingRetries > 0 && e.toString().contains('Connection reset by peer')) {
      return await _getWithRetry(url, remainingRetries - 1);
    }
    throw e;
  }
}

调用时用_getWithRetry(url, 2)即可尝试最多3次请求。

  • 前置网络检查:在发起请求前检查设备网络状态,减少无效请求(可借助connectivity_plus包实现)。

内容的提问来源于stack exchange,提问作者Saad Bashir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:32:45