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

Flutter应用连接API遇SocketException连接超时错误,求解决方案

解决Flutter请求API连接超时问题

问题描述

我尝试将Flutter应用与API连接,编写了如下GET请求代码:

Future<void> fetchData() async {
        final String apiUrl = 'http://192.168.100.90:4002/booking/getall';
        try {
          // Making GET request
          final response = await http.get(Uri.parse(apiUrl));
          print(response.statusCode);
          // Decoding response
          if (response.statusCode == 200) {
            // If the server returns a 200 OK response,
            // parse the JSON
            final Map<String, dynamic> responseData = json.decode(response.body);

            // Process the data here if needed
            print(responseData);
          } else {
            // If the server did not return a 200 OK response,
            // throw an exception
            throw Exception('Failed to load data');
          }
        } catch (e) {
          // Error handling
          print('Error: $e');
          throw e;
        }
      }

运行时出现以下错误:

I/flutter ( 2707): Error: ClientException with SocketException: Connection timed out (OS Error: Connection timed out, errno = 110), address = 192.168.100.90, port = 48130, uri=http://192.168.100.90:4002/booking/getall
E/flutter ( 2707): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: ClientException with SocketException: Connection timed out (OS Error: Connection timed out, errno = 110), address = 192.168.100.90, port = 48130, uri=http://192.168.100.90:4002/booking/getall

解决方案

  • 检查网络连通性

    1. 确认Flutter设备(模拟器/真机)与API服务器处于同一局域网(如同一WiFi)
    2. 在设备浏览器中直接访问http://192.168.100.90:4002/booking/getall,若无法访问,问题出在API服务器而非Flutter代码
  • 验证API服务器状态

    1. 确认服务器程序正在运行,且监听端口为4002
    2. 检查服务器防火墙/安全组设置,确保4002端口允许局域网设备访问
    3. Android模拟器访问本地服务器时,需将192.168.100.90替换为10.0.2.2(模拟器的本地回环映射地址);iOS模拟器可直接使用局域网IP或localhost
  • 设置请求超时
    主动添加超时限制,避免无限等待:

    final response = await http.get(Uri.parse(apiUrl)).timeout(
      const Duration(seconds: 10),
      onTimeout: () {
        throw Exception('请求超时,请检查网络或服务器');
      },
    );
    
  • 配置网络权限
    Android端:在android/app/src/main/AndroidManifest.xml中添加权限

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

    iOS端:在ios/Runner/Info.plist中添加HTTP请求允许配置(正式环境建议改用HTTPS并配置ATS规则)

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
    </dict>
    

内容的提问来源于stack exchange,提问作者satyam gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:37:48