【问题标题】:Trying to consume content-type [text/json] with Spring Boots's RestTemplate尝试使用 Spring Boots 的 RestTemplate 使用内容类型 [text/json]
【发布时间】:2019-12-07 06:11:33
【问题描述】:

服务器正在给我一个内容类型为text/json 的响应,我需要将它消耗到Java 类中。当服务器的响应是内容类型application/json 时,我可以做到这一点。当我使用 Spring Boot 使用 text/json 内容类型时,如何实现与使用 application/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]

【问题讨论】:

    标签: java json spring rest spring-boot


    【解决方案1】:

    您需要将转换器添加到其余模板。请参考Answer 1Answer 2

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

    【讨论】:

    • 我假设这将适用于内容类型text/plain,就像您使用MediaType.TEXT_PLAIN 提供的第一个link 一样,但我需要使用内容类型text/json。我希望 Spring Boot 具有这样做的功能。
    猜你喜欢
    • 2017-10-08
    • 2019-06-23
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多