No HttpMessageConverter for XXXDto and content type “application/x-www-form-urlencoded“

在尝试用HttpEntity发送POST请求时,初始设置contentType为application/x-www-form-urlencoded并直接使用DTO导致报错。解决方案是改用MultiValueMap填充参数,正确构建HttpEntity,从而成功调用第三方系统并获取响应。

今天在调用一个第三方的系统的时候,需要把请求头的content type 设置为application/x-www-form-urlencoded,我开始的时候就直接使用dto包装到HttpEntity,结果一直报错。

具体代码如下:

TokenReqDto tokenReqDto = new TokenReqDto();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<TokenReqDto> entity = new HttpEntity<>(tokenReqDto,headers);
        ResponseEntity<TokenRespDto> resp = restTemplate.postForEntity(identityUrl,entity, TokenRespDto.class);
        return resp;

经过分析查询,是要修改为用MultiValueMap来填充参数,dto的方式spring 识别不了。

修改后的代码如下,具体的业务参数我就删了。

HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "client_credentials");
        params.add("client_type", "service");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<TokenRespDto> tokenEntity = restTemplate.exchange(identityUrl, HttpMethod.POST, requestEntity, TokenRespDto.class);
        return tokenEntity;

然后部署验证,发现成功了。

这个错误表明在Spring框架中,当尝试将HTTP请求中的`application/x-www-form-urlencoded`内容转换为`java.util.HashMap`时,系统找不到合适的`HttpMessageConverter`来处理这种转换。 ### 原因分析: 1. **缺少合适的转换器**:Spring默认的`HttpMessageConverter`列表可能不包含能够处理`x-www-form-urlencoded`到`HashMap`的转换器。 2. **请求格式不匹配**:如果客户端发送的是`x-www-form-urlencoded`数据,但服务端期望的是JSON或其他格式,也会导致此错误。 3. **未正确配置转换器**:可能需要手动添加`FormHttpMessageConverter`或其他支持表单数据的转换器。 ### 解决方法: 1. **确保使用`@RequestParam`或`MultiValueMap`**: 如果接收的是表单数据,建议使用`@RequestParam`注解或`MultiValueMap`而不是`HashMap`。例如: ```java public ResponseEntity<?> handleForm(@RequestParam Map<String, String> params) { ... } ``` 或 ```java public ResponseEntity<?> handleForm(MultiValueMap<String, String> formData) { ... } ``` 2. **显式配置`FormHttpMessageConverter`**: 在Spring MVC配置中添加表单数据转换器: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new FormHttpMessageConverter()); } } ``` 3. **检查请求的`Content-Type`**: 确保客户端发送的`Content-Type`头是`application/x-www-form-urlencoded`,且数据格式正确(如`key1=value1&key2=value2`)。 4. **改用JSON格式**: 如果可行,将客户端和服务器端统一改为使用JSON格式(`Content-Type: application/json`),并配置`Jackson`等JSON转换器。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值