Flutter应用连接C# API时遇连接拒绝与无效主机问题
Flutter 迁移中API连接问题排查与解决
问题背景
原本在Android Studio开发的应用可将输入数据保存至数据库,现在迁移到Flutter平台时,遇到API连接异常问题。
问题详情
调用postDataToApi方法时,使用http://localhost:54553/api/TicketAPI/作为基础URL会直接出现连接拒绝错误;尝试用10.0.2.2替代localhost后,又触发无效主机错误。
代码示例
import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; class TicketInfoApi { static const String _baseUrl = 'http://localhost:54553/api/TicketAPI/'; static Future<bool> postDataToApi({ required String officerNumber, required int officerRank, String ticketNumber = "123rest", required String officerFirstName, required String officerLastName, }) async { final String apiUrl = '${_baseUrl}InsertTicket'; final body = json.encode({ 'officerNumber': officerNumber, 'ticketNumber': ticketNumber, 'officerFirstName': officerFirstName, 'officerLastName': officerLastName, }); try { final response = await http.post( Uri.parse(apiUrl), headers: { HttpHeaders.contentTypeHeader: 'application/json', }, body: body, ); if (response.statusCode == 200) { final responseData = json.decode(response.body); return responseData != null; } else { return false; } } catch (error) { return false; } } }
排查与解决步骤
- 确认API服务的绑定地址:本地API服务不能仅绑定
localhost,需改为绑定0.0.0.0(允许所有网络接口访问)或者本机的局域网IP(如192.168.x.x)。如果服务只监听localhost,模拟器无法跨网络访问到主机的服务。 - 使用正确的IP访问:
- Android模拟器中,
10.0.2.2是主机localhost的映射地址,但前提是API服务已允许外部访问; - 更稳妥的方式是直接使用主机的局域网IP替换
localhost,这样模拟器或真机都能正常访问。
- Android模拟器中,
- 检查防火墙设置:确保主机防火墙允许
54553端口的入站连接,否则模拟器的请求会被拦截。 - 验证API服务可用性:先用浏览器或Postman访问
http://[主机IP]:54553/api/TicketAPI/InsertTicket,确认服务能正常响应,排除API本身的故障。 - 处理无效主机/跨域问题:若使用
10.0.2.2出现无效主机错误,大概率是后端CORS配置未允许该来源的请求,需在API后端添加对应的跨域规则;同时检查Flutter项目的网络权限:Android需在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET"/>,iOS需在Info.plist中配置ATS允许HTTP请求(若API未使用HTTPS)。
内容的提问来源于stack exchange,提问作者unknown techh
相关产品推荐
相关产品推荐

