Consuming HAL-based REST service with spring-hateoas

前端 未结 4 1344
一生所求
一生所求 2021-01-14 22:02

I\'m trying to consume a HAL-based REST service with the RestTemplate class. The response body looks like this:

{
  \"_embedded\": {
    \"school:teachers\":         


        
相关标签:
4条回答
  • 2021-01-14 22:09

    I tried a similar approach to what Vishnoo Rath. I am planning to build a common method to do this for all my resources.

    ResponseEntity<String> response = 
                    restTemplate.exchange("http://localhost:8081/rest/cars", HttpMethod.GET, null, String.class);
    
            String data = response.getBody();
            //log.info(data);
    
            ObjectMapper om = new ObjectMapper();
            om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
            JsonNode jsNode = om.readTree(data);
            String test = jsNode.at("/_embedded/cars").toString();
            //log.info(test);
    
            ArrayList<Car> cars = om.readValue(test, new TypeReference<List<Car>>() {
            });
    
            for (Car theCar : cars) {
                log.info(">>> " + theCar.getMake() + " " + theCar.getModel() + " " + theCar.getYear());
            }
    
    0 讨论(0)
  • 2021-01-14 22:21

    I use Bowman to consume JSON+HAL resources in JAVA. This library greatly simplifies the consumption of resources comparing to RestTemplate as shown in this article.

    0 讨论(0)
  • 2021-01-14 22:28

    I too faced a similar problem. And the way I chose to work around it is :

            ResponseEntity<String> response = restTemplate.exchange(
                    "http://localhost:8080/payment/search/findByApprovalDate?approvalDate=2017-11-06", HttpMethod.GET,
                    null, String.class);
    
            String data = response.getBody();
    
            ObjectMapper om = new ObjectMapper();
            om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
            JsonNode jsNode = om.readTree(data);
            String test = jsNode.at("/_embedded/payment").toString();
    
            payments = om.readValue(test, new TypeReference<List<RHPayment>>() {
            });
    
    0 讨论(0)
  • 2021-01-14 22:36

    Definitely, you should go with Traverson

    Traverson client = new Traverson(new URI("http://localhost:8080/api/"), 
             MediaTypes.HAL_JSON);
        Resources<Resource<Teacher>> teachers = client
            .follow("school:teachers")
            .toObject(new ResourcesType<Resource<Teacher>>(){});
    

    https://docs.spring.io/spring-hateoas/docs/current/reference/html/#client.traverson

    0 讨论(0)
提交回复
热议问题