Flutter应用通过http包无法连接FastAPI的问题求助
解决Flutter调用FastAPI接口的连接问题
问题背景
在物理设备上运行Flutter应用且已授予网络权限,但调用FastAPI接口时先出现「Connection timed out」错误;改用uvicorn main:app --reload --host 0.0.0.0启动API并替换请求地址为本地IP后,又出现「Connection refused」错误。FastAPI在网页端可正常访问。
解决方案步骤
1. 确保设备与服务器在同一局域网
物理手机和运行FastAPI的电脑必须连接同一个WiFi网络,禁止跨网络访问(比如电脑连WiFi、手机用数据流量,或分属不同WiFi)。
2. 获取电脑的局域网IP
- Windows:打开命令提示符,执行
ipconfig,找到「无线局域网适配器 WLAN」下的IPv4地址 - macOS/Linux:打开终端,执行
ifconfig或ip addr,找到对应WiFi网卡的inet地址 - 验证:在手机浏览器中访问
http://[你的局域网IP]:8000/docs,若能打开FastAPI文档页面,说明网络连通性正常。
3. 正确启动FastAPI服务
必须使用以下命令启动,确保服务监听所有网卡:
uvicorn main:app --reload --host 0.0.0.0 --port 8000
--host 0.0.0.0表示允许局域网内所有设备访问该服务,仅用--reload默认只监听本地127.0.0.1,物理设备无法访问。
4. 检查电脑防火墙/安全软件
电脑防火墙可能拦截8000端口的入站请求:
- 临时关闭防火墙测试,若能连接,再添加规则允许8000端口的入站连接
- 部分杀毒软件也会拦截网络请求,可暂时关闭验证
5. 修改Flutter代码中的请求地址
将原代码中的10.0.2.2替换为你的局域网IP,并添加异常捕获方便调试:
Future<void> sendLongText(String input_text) async { // 替换为你的局域网IP const url = 'http://192.168.1.100:8000/post_input/'; print('res start'); try { final response = await http.post( Uri.parse(url), headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'input_text': input_text, 'model': 'T5', 'min_length': 40, 'max_length': 80 }) ); print('Response status: ${response.statusCode}'); print('Response body: ${response.body}'); } catch (e) { print('Error: $e'); } print('res end'); }
内容的提问来源于stack exchange,提问作者RandomGuy
相关产品推荐
相关产品推荐

