【问题标题】:How to set accept media type in RestTemplate (Spring restful client)如何在 RestTemplate 中设置接受媒体类型(Spring restful 客户端)
【发布时间】:2013-08-20 05:30:55
【问题描述】:

默认情况下,我从 spring restful 服务获取 xml 响应。 在我的 Spring RESTful 客户端中使用 RestTemplate 如何将接受媒体类型配置为 JSON?

【问题讨论】:

    标签: java spring rest


    【解决方案1】:

    如果 Rest Service 只生成 XML,那么我认为您不能接受它作为 JSON。在这种情况下,您需要在 Rest Service 中将 MediaType 添加为 "application/json" 以及现有的 xml 响应。

    例如,在 Spring Restful Service 中,注释将是

    @RequestMapping(value = "/myurl", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    

    如果 Rest Service 正在生成 Json 和 Xml,那么在 rest 客户端中你需要这样做:

    ResponseEntity<YourClass> apiResp = restTemplate.exchange(url, HttpMethod.GET, request, YourClass.class);
    YourClass output=apiResp.getBody();
    

    【讨论】:

    • 我意识到我使用的是 spring 3.0.x,其中没有生产和消费。现在我将我的应用程序升级到最新版本的 spring,然后我能够按预期获得 json 响应。
    猜你喜欢
    • 2016-07-17
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2014-07-01
    • 2016-01-17
    • 2016-05-14
    • 2016-07-16
    相关资源
    最近更新 更多