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

Flutter向FastAPI发送POST请求出现连接超时错误求助

解决Flutter调用FastAPI情感分析服务超时问题

问题背景

FastAPI服务通过Swagger测试正常,但Flutter端发送POST请求时出现连接超时,无法获取情感分析结果并赋值给sentiment变量。

排查与解决步骤

1. 修正FastAPI服务绑定地址

FastAPI默认仅绑定127.0.0.1,仅本地可访问。启动服务时需指定监听所有网卡:

uvicorn main:app --host 0.0.0.0 --port 8000

这样服务会监听主机所有IP的8000端口,模拟器可通过10.0.2.2正常访问。

2. 验证网络连通性

  • 在Android模拟器中执行adb命令测试请求:
adb shell curl -X POST http://10.0.2.2:8000/predict -H "Content-Type: application/json" -d '{"text":"test"}'
  • 如果请求失败,检查主机防火墙是否开放8000端口的入站规则,允许模拟器所在网络访问。

3. 添加Flutter应用网络权限

  • Android:在AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • iOS:在Info.plist中添加HTTP请求允许配置:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

4. 增加请求超时与异常捕获

Flutter默认请求超时时间较短,手动设置超时并捕获异常避免崩溃:

RoundButton(
    title: 'detect sentiment',
    onPress: () async {
        var url = Uri.parse('http://10.0.2.2:8000/predict');
        var data = {
            'text': descriptionController.text.toString()
        };
        var body = json.encode(data);
        var headers = {'Content-Type': 'application/json'};

        try {
            var response = await http.post(
                url,
                headers: headers,
                body: body,
            ).timeout(const Duration(seconds: 10));
            
            if (response.statusCode == 200) {
                sentiment = response.body;
                print('情感分析结果: $sentiment');
            } else {
                print('请求失败: ${response.statusCode}');
            }
        } on TimeoutException catch (_) {
            print('请求超时,请检查网络连接');
        } on SocketException catch (_) {
            print('网络连接异常,请确认服务是否启动');
        } catch (e) {
            print('未知错误: $e');
        }
    }
),

5. 配置FastAPI跨域(CORS)

若存在跨域限制,在FastAPI中添加CORS中间件:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 允许的来源,根据实际情况调整
origins = [
    "http://10.0.2.2",
    "http://10.0.2.2:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 原有predict接口代码保持不变
@app.post('/predict')
def predict_sentiment(data: SentimentData):
    data = data.dict()
    text = data['text']
    output = predict(vectoriser, LRmodel, text)
    prediction = "positive" if output == 1 else "negative"
    return prediction

内容的提问来源于stack exchange,提问作者Abhishek Mullackal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:32:41