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

API请求返回415错误但未传媒体文件(Postman可用模拟器报错)

问题:Flutter请求API返回415错误(Postman可正常运行)

我尝试通过API向服务器添加地址,模拟器中返回Error 415错误,但我仅发送JSON数据,未附带任何媒体文件。该请求在Postman中能正常执行,但在Flutter模拟器里报错。

API请求函数

Future addAddress(Placemark placemark) async {
try {
  String token = DataSaver.getData(tokenKey);

  Uri uri = Uri.parse("$url$usersTag/$uid$addressTag");
  var response = await http
      .post(
    uri,
    headers: <String, String>{
      'userId': uid,
      "Authorization": "Bearer $token",
    },
    body: json.encode(AddressCredintials.fromPlacemark(placemark)),
  )
      .timeout(timeoutDuration, onTimeout: () {
    log("request TimeOut");
    return http.Response('Error', 408);
  });

  print(response.body.toString());
  if (response.statusCode == 200) {
    log("address added");
  } else {
    print(response.statusCode);
  }
} catch (e) {
  print(e);
} }

数据类代码

class AddressCredintials {
  String govID;
  String cityID;
  String? villageID;
  String street;
  String? building;
  String? apartment;

  AddressCredintials(
      {this.apartment,
      this.building,
      required this.street,
      required this.cityID,
      required this.govID,
      this.villageID});

  factory AddressCredintials.fromPlacemark(Placemark placemark) {
    return AddressCredintials(
        street: placemark.street,
        cityID: placemark.city.id,
        govID: placemark.government.id,
        apartment: placemark.apartment,
        building: placemark.building,
        villageID: placemark.village != null ? placemark.village!.id : null);
  }

  Map toJson() {
    return {
      "governorateId": govID,
      "cityId": cityID,
      "areaId": villageID,
      "street": street,
      "buildingNo": building,
      "appartmentNo": apartment
    };
  }
}

解决办法

Error 415代表服务器不支持请求的媒体类型,核心问题是你的请求头缺少Content-Type: application/json。Postman会自动为JSON请求添加该头,但Flutter的http.post方法不会默认配置这个参数。

修改请求头,新增Content-Type配置即可:

headers: <String, String>{
  'userId': uid,
  "Authorization": "Bearer $token",
  'Content-Type': 'application/json', // 新增此行
},

另外,从你的toJson方法来看,JSON结构是合规的,无需额外调整格式,补全请求头即可解决问题。

内容的提问来源于stack exchange,提问作者Abulrahman Hejazi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:06:15