Spring Data REST - Consume List of Entities, Java HATEOAS client

元气小坏坏 提交于 2019-11-29 11:41:24
JudgingNotJudging

I solved this by doing a few things.

  1. I had to update to spring-hateoas:0.20.0.RELEASE from 0.19.0. spring-hateoas:0.19.0 did not support jackson 2.7+ as specified here.

  2. I updated my Client to call as below.

    ObjectMapper mapper = builder.build()
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    
    messageConverter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"))
    messageConverter.setObjectMapper(mapper)
    
    ResponseEntity<PagedResources<MyEntity>> responseEntity =
            new RestTemplate(Arrays.asList(messageConverter))
                    .exchange(
                    uri,
                    HttpMethod.GET,
                    HttpEntity.EMPTY,
                    new ParameterizedTypeReference<PagedResources<MyEntity>>() {}, port
            )
    

PagedResources now looks like this:

<200 OK,PagedResource { content: [{<List of MyEntities>}], metadata: Metadata { number: 0, total pages: 1, total elements: 10, size: 20 }, links: [<List of hateoas links for MyEntities>] },{Server=[Apache-Coyote/1.1], Content-Type=[application/hal+json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Thu, 21 Jul 2016 14:57:18 GMT]}>

@zeroflagL's comment got me looking more closely at the PagedResources implementation, which eventually led to the 'aha!' moment with this blog.

The relevant bit is that the default RestTemplate doesn't set the accept header to application/hal+json. Instead, the default is application/x-spring-data-compact+json;charset=UTF-8 which has not content and only links. This is why I was getting empty content for my Resources types. Explicitly setting the MediaType as above fixed the issue.

Here is my solution:

    ParameterizedTypeReference<PagedResources<EntityObject>> responseType;
    responseType = new ParameterizedTypeReference<PagedResources<EntityObject>>() { };

    ResponseEntity<PagedResources<EntityObject>> pageResources;
    pageResources = restTemplate
            .withBasicAuth(username, password)
            .exchange(
                    UriComponentsBuilder.fromPath("/your/api/path").build().toString(),
                    GET,
                    null,
                    responseType
            );

    PagedResources<EntityObject> resource = pageResources.getBody();
    assertTrue(resource.getContent().isEmpty());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!