尝试使用Spring Boots的RestTemplate消费内容类型[text / json]

时间:2019-07-29 21:35:35

标签: java json spring rest spring-boot

服务器给我一个内容类型为text/json的响应,我需要将其使用到Java类中。当服务器的响应为内容类型application/json时,我可以做到这一点。如何使用Spring Boot消耗application/json内容类型时实现与使用text/json内容类型时相同的功能?

我尝试创建一个HttpHeaders对象,然后创建setContentType方法,但据我所知,MediaType选项均不适用于text/json

Request req = new Request();
String url = "<url>";

HttpHeaders headers = new HttpHeaders();
headers.setContentType( MediaType.TEXT_JSON ); // this isn't valid but is where I have tried setting the content-type to text/json
HttpEntity< Request > entity = new HttpEntity<>( req, headers );
ResponseEntity< Response > resp = 
    restTemplate.exchange( url, HttpMethod.POST, entity, Response.class );

Request是确定服务器响应的类,而Response是返回的json的Java表示。

理想情况下,返回的json将存储到Response类中,但我收到此错误:InvocationTargetException: Failed to execute CommandLineRunner: Could not extract response: no suitable HttpMessageConverter found for response type [class Response] and content type [text/json]

1 个答案:

答案 0 :(得分:0)

您需要将转换器添加到其余模板中。请参阅此Answer或此Answer

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