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

Spring 6 RestClient发送表单编码请求报错求助

解决RestClient调用时400 Bad Request(unsupported_grant_type)问题

你遇到的unsupported_grant_type错误,本质是服务端未正确解析到请求中的grant_type参数,核心原因是RestClient发送的请求格式和RestTemplate不一致。

在RestTemplate代码中,你通过HttpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED)指定了表单编码格式,配合MultiValueMap作为请求体,RestTemplate会自动将其编码为key=value&key=value的表单格式发送给服务端,这是符合接口要求的。

但你的RestClient代码直接复用了原有的HttpEntity对象,RestClient对HttpEntity的处理逻辑和RestTemplate存在差异,导致请求体没有被正确编码成服务端期望的表单格式,进而触发参数解析失败的错误。

修复后的代码

直接在RestClient的请求构建链中显式设置Content-Type,并传入MultiValueMap作为请求体,无需封装成HttpEntity:

// 定义表单参数(和原有代码一致)
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", "aaa");
map.add("password", "bbc");
map.add("grant_type", "password");

// 构建RestClient并发送请求
RestClient test = RestClient.builder()
        .baseUrl("https://dev-test.com/")
        .build();

ResponseEntity<String> responseLicenseCheck = test.post()
        .uri("/token")
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(map)
        .retrieve()
        .toEntity(String.class);

这种写法和RestTemplate的行为完全一致,请求会以application/x-www-form-urlencoded格式发送,服务端能正确解析所有表单参数,即可解决400错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:25:03