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

求助:Flutter调用Django后端时出现Unsupported media type请求错误

Fixing "Unsupported media type 'text/plain; charset=utf-8'" in Flutter-Django API Call

Hey there! That error message is spelling out exactly what's going wrong—your Django backend doesn't recognize the format of the data you're sending from Flutter. Let's work through this:

Why the error pops up

Django REST Framework expects POST requests with JSON data to include a Content-Type header set to application/json. Right now, your Flutter request isn't specifying this header, so it defaults to text/plain; charset=utf-8—a format Django doesn't know how to process for API endpoints.

The simple fix

All you need to do is add the missing Content-Type header to your http.post call. Here's your updated code:

Future<void> addAlbum(Album album) async {
  print('5');
  final url = Uri.parse('http://127.0.0.1:8000/list-create/');
  try {
    print('6');
    final response = await http.post(url,
      headers: {
        'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f',
        // Add this line to tell Django you're sending JSON
        'Content-Type': 'application/json',
      },
      body: json.encode({
        'title': album.title,
        'cover': album.cover, // => this is an int
        'photos_number': album.photos_number, // => this is an int
      }));
    print('6 ed');
    final responseData = json.decode(response.body);
    print(responseData.toString());
    final newAlbum = Album(
      title: album.title,
      cover: album.cover,
      photos_number: album.photos_number,
    );
    print('6 edddgg');
    _items.add(newAlbum);
    print('6 f');
    notifyListeners();
  } catch (error) {
    print('7');
    print(error);
    throw error;
  }
}

Quick extra checks

  • Make sure album.cover and album.photos_number are actually integers (not strings) before encoding—Django will throw validation errors if the data types don't match your model's expectations.
  • Double-check that your authorization token is still valid (expired tokens cause separate issues, but it's good to confirm while you're at it).

Once you add that header, your Django backend should correctly parse the JSON data from Flutter, and the error should vanish!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:57:32