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

Flutter Dio配置求助:POST请求返回400状态码排查

问题排查与修复方案

核心问题分析

你的代码存在三个关键错误,直接导致了400状态码错误:

1. 请求参数传递位置错误

服务器要求接收application/json格式的请求体,但你在SignInRepository的login方法中,把登录参数传给了queryParameters(该参数会将数据拼在URL上),而非对应请求体的data参数。Postman/Swagger测试时参数是放在请求体里的,代码传递方式与测试场景不匹配,服务器无法识别有效参数,返回400。

2. Content-Type格式错误

NetworkRequestUtil的BaseOptions中,contentType写成了"application/json: charset=utf-8",正确的分隔符应该是分号;而非冒号:,错误的Content-Type会导致服务器无法正确解析请求体。

3. 异步调用与异常捕获不完整

processLogin方法调用login时未使用await,无法等待请求完成;同时login的异常未被捕获,出现未处理的全局异常。


修复后的代码片段

1. 修正NetworkRequestUtil的Content-Type

NetworkRequestUtil._internal() {
  BaseOptions options = BaseOptions(
      baseUrl: AppConstants.APP_BASE_URL,
      connectTimeout: Duration(seconds: 10),
      receiveTimeout: Duration(seconds: 5),
      headers: {},
      contentType: "application/json; charset=utf-8", // 替换冒号为分号
      responseType: ResponseType.json);
  dio = Dio(options);
}

2. 修正SignInRepository的参数传递

class SignInRepository{
  login({SignInModel? signInModel}) async {
    // 将参数从queryParameters改为data,放入请求体
    var response = await NetworkRequestUtil()
        .post(AppConstants.LOGIN_URL, data: signInModel?.toJson());
    print("The response from the repository is ${response.toString()}");
    return response;
  }
}

3. 修正processLogin的异步调用与异常捕获

Future <void> processLogin(SignInModel signInModel)async {
  EasyLoading.show(
    indicator: CircularProgressIndicator(),
    maskType: EasyLoadingMaskType.clear,
    dismissOnTap: true
  );
  try{
    // 添加await等待请求完成
    var result = await locator.get<SignInRepository>().login(signInModel:signInModel);
    print("The result is ${result.toString()}");
    EasyLoading.dismiss();
  }catch(e){
    EasyLoading.dismiss();
    toastInfo(msg: e.toString());
  }
}

额外调试建议

给Dio添加日志拦截器,打印完整请求信息(URL、Header、请求体),方便和Postman的请求对比,快速定位差异:

dio.interceptors.add(LogInterceptor(
  requestBody: true,
  responseBody: true,
));

内容的提问来源于stack exchange,提问作者Ukeme Elijah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:46:04