【问题标题】:Get RAW-Response from RestTemplate从 RestTemplate 获取 RAW-Response
【发布时间】:2021-01-05 08:49:08
【问题描述】:

我正在尝试从 Spring RestTemplate 中检索原始响应

String get = restTemplate.postForObject(url, params, String.class);

但是由于服务器以Content-Type: Application/Json 响应,Spring 尝试通过解析将响应映射到字符串对象。在我的情况下,这导致

Cannot deserialize instance of `java.lang.String` out of START_ARRAY token

因为响应包含一个 json 数组。是否可以在不解析的情况下获得原始响应?还是我必须使用 RestTemplate 以外的东西?

你可以用这些例子来试试这个问题

restTemplate.getForEntity("https://api.github.com/users/hadley/orgs", String.class);
restTemplate.getForObject("https://api.github.com/users/hadley/orgs", String.class);

【问题讨论】:

  • baeldung.com/rest-template - 使用 postforEntity
  • @MarcStröbel 这会产生同样的错误
  • 是否有为此 resttemplate 实例注册的自定义反序列化程序?如果使用普通的新 RestTemplate 也会出现同样的错误?
  • 也许还添加您正在使用的 Spring/Spring boot 版本。
  • @MarcStroebel 你在哪里对,我的 spring 应用程序中似乎配置了一个强制消息转换器 MappingJackson2HttpMessageConverter

标签: java spring resttemplate


【解决方案1】:

这应该会导致响应实体包含字符串。

ResponseEntity<String> response = restTemplate.postForEntity(url, null, String.class)

【讨论】:

  • postForEntity 和 postForObject 产生同样的问题
  • @wutzebaer 这很有趣,你能用更多信息更新你的问题吗?
  • 我添加了您可以尝试的示例
  • @wutzebaer 它与您的示例完美配合。看起来它与您的应用程序配置有关。尝试创建 RestTemplate 的新实例,而不是从 Spring 上下文中获取它,我们会知道这就是问题所在。
【解决方案2】:

请按照代码尝试

 @GetMapping(path = "raw")
    public String raw() {
        String response = restTemplate.getForObject("http://jsonplaceholder.typicode.com/users", String.class);
        System.out.println("Length: " + response.length());
        return response;
    }

我的 RestTemplate 看起来像这样

@Configuration
    public static class Beaner {
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多