Flutter应用连接API遇SocketException连接超时错误,求解决方案
问题描述
我尝试将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
解决方案
检查网络连通性
- 确认Flutter设备(模拟器/真机)与API服务器处于同一局域网(如同一WiFi)
- 在设备浏览器中直接访问
http://192.168.100.90:4002/booking/getall,若无法访问,问题出在API服务器而非Flutter代码
验证API服务器状态
- 确认服务器程序正在运行,且监听端口为4002
- 检查服务器防火墙/安全组设置,确保4002端口允许局域网设备访问
- 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

