使用Retrofit发送请求时遭遇Http 415状态码错误
Retrofit请求返回415错误的解决办法
问题分析
415状态码表示服务器不支持请求发送的媒体类型。你已在请求头设置Accept: application/json和Content-Type: application/json,但核心问题是请求体未被正确序列化为JSON字符串:
你的@Body()参数是Map<String, String>类型,Retrofit生成的代码直接将该Map作为请求体传给Dio,但Dio默认会把Map以application/x-www-form-urlencoded格式发送——即便你设置了Content-Type头,实际请求体格式仍不符合服务器要求,最终触发415错误。
解决方法
方法1:用实体类替代Map(推荐)
配合json_serializable插件让Retrofit自动处理JSON序列化:
- 定义实体类:
import 'package:json_annotation/json_annotation.dart'; part 'user_request.g.dart'; @JsonSerializable() class UserRequest { final String name; final String email; UserRequest({required this.name, required this.email}); factory UserRequest.fromJson(Map<String, dynamic> json) => _$UserRequestFromJson(json); Map<String, dynamic> toJson() => _$UserRequestToJson(this); }
- 修改Retrofit接口:
@POST('/users') Future<dynamic> users( @Body() UserRequest request, @Header('accept') String accept = 'application/json', @Header('content-type') String contentType = 'application/json', );
重新生成代码后,Retrofit会自动调用toJson()将实体类转为JSON字符串发送,确保请求体格式正确。
方法2:手动将Map序列化为JSON字符串
若不想用实体类,可手动把Map转成JSON字符串后传入:
- 修改Retrofit接口:
import 'dart:convert'; @POST('/users') Future<dynamic> users( @Body() String request, @Header('accept') String accept = 'application/json', @Header('content-type') String contentType = 'application/json', );
- 调用接口时传入序列化后的字符串:
final requestMap = {'name': 'test', 'email': 'test@example.com'}; final jsonString = jsonEncode(requestMap); await apiService.users(jsonString);
方法3:全局配置Dio转换器
初始化Dio时设置默认转换器,确保Map类型请求体被序列化为JSON:
final dio = Dio() ..options.contentType = Headers.jsonContentType ..transformer = DefaultTransformer();
此方法全局生效,适合所有请求均需JSON格式的场景。
内容的提问来源于stack exchange,提问作者genericUser
相关产品推荐
相关产品推荐

