Flutter POST请求ContentType头未生效导致expires_in参数异常
问题排查:Dart调用Dolby.io Auth接口无法生效expires_in参数
核心问题出在请求体格式与Content-Type不匹配:
你代码里虽然设置了Content-Type: application/x-www-form-urlencoded,但请求体用jsonEncode生成了JSON字符串,而Dolby.io的这个接口需要的是表单键值对格式(也就是grant_type=client_credentials&expires_in=7200这种形式)。接口解析时识别不到JSON格式里的expires_in参数,所以只能使用默认的3600秒有效期。
修正后的代码
把请求体直接传Map<String, String>类型,不需要jsonEncode——http包会自动将Map编码成符合application/x-www-form-urlencoded要求的格式:
Future<http.Response> getPrivateKeyResponse() async { var customerKey = "***"; var customerSecret = "***"; var encode = base64Encode(utf8.encode("$customerKey:$customerSecret")); return await http.post( Uri.parse('https://api.dolby.io/v1/auth/token'), headers: <String, String>{ "Authorization":"Basic $encode", "Content-Type": "application/x-www-form-urlencoded" }, body: <String, String>{ "grant_type":"client_credentials", "expires_in":"7200" // 表单值需为字符串,接口会自动解析为数字 }, ); }
关键说明
expires_in必须以字符串形式传入,因为表单数据的所有值都是字符串类型,接口会自动转换为数字处理- 当body传入
Map<String, String>时,http包会自动处理编码,即使你不手动指定Content-Type,也会自动添加正确的头(当然手动指定也没问题) - 之前的JSON格式请求体,只有当
Content-Type设为application/json时才会被接口正确解析,但Dolby.io的这个认证接口不支持JSON格式的请求体,只接受表单格式
内容的提问来源于stack exchange,提问作者Yunnane
相关产品推荐
相关产品推荐

