当前位置: 代码迷 >> java >> HttpMessageConverter 异常:RestClientException:无法写入请求:找不到合适的 HttpMessageConverter
  详细解决方案

HttpMessageConverter 异常:RestClientException:无法写入请求:找不到合适的 HttpMessageConverter

热度:22   发布时间:2023-07-26 14:52:27.0

我正在编写一个客户端来使用 RESTful 服务。 我需要以键值对的形式发送请求,他们建议我为此使用 Map。 我正在调用的 RESTful 服务将只接受 JSON,而我的客户端将使用 Java。 它实际上将成为现有企业 EJB 项目的一部分。

我已经编写了一个客户端并且能够成功调用 RESTful 服务。 事实上,如果我以字符串(JSON 格式)发送请求,那么我什至会得到响应。 但我想避免这种将 Map 转换为 JSON 格式字符串然后在 Request 中发送出去的手动工作。

我已将 Content-Type 设置为 application/json 并创建了一个包含 KeyValue 对的 Map。

来自客户端的代码片段:

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(MyConstants.JWT_AUTH_TOK, restUtil.getJWTToken());

restTemplate = new RestTemplate();

ModelReqVO modVO = new ModelReqVO();
Map<String, String> dataMap = new HashMap<String, String>();
//Setting key,value into datamap (e.g. "key1", "value1")
modVO.setDataMap(dataMap);

ResponseEntity<ModelRspnsVO> result = restTemplate.postForEntity(mySrvcFN, new HttpEntity(modVO, headers), ModelRspnsVO.class);

请求(ModelReqVO)类:

public class ModelReqVO {

private HashMap<String, String> dataMap;

ModelReqVO() {
    this.dataMap = new HashMap<String, String>();
}

//getter and setter generated
}

这是我得到的例外-

RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [com.mycomp.myproj.ModelReqVO] and content type [application/json].

我检查了我的 restTemplate 上的 HttpMessageConverters,我确实找到了 MappingJacksonHttpMessageConverter。 代码中是否还需要其他东西才能使用上述转换器?

我在 Spring.io 论坛上找到了几个例子,但它们是关于需要 www/form 内容而不是 JSON 的服务。 令人惊讶的是,我没有找到有关使用特定转换器将 Map 作为 JSON 发送的任何详细信息。

注意:代码片段可能有编译错误,我已经从我的手机中输入了代码。 出于安全原因,我无法在我编码的机器上使用互联网。

该错误消息说,没有合适的HttpMessageConverter发现请求类型,所以只需添加MappingJackson2HttpMessageConverterMediaTypeRestTemplate

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 
coverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON); 
restTemplate.getMessageConverters().add(0, converter)