gpt4 book ai didi

java - 使用 spring-hateoas 使用基于 HAL 的 REST 服务

转载 作者:行者123 更新时间:2023-12-05 02:18:20 24 4
gpt4 key购买 nike

我正在尝试使用 RestTemplate 类使用基于 HAL 的 REST 服务。响应正文如下所示:

{
"_embedded": {
"school:teachers": [
{
"name": "Adams",
"state": "CA",
"_links": {
"self": {
"href": "http://localhost:8080/api/teachers/1"
}
}
},
{
"name": "Barnes",
"state": "FL",
"_links": {
"self": {
"href": "http://localhost:8080/api/teachers/2"
}
}
},
{
"name": "Armstrong",
"state": "GA",
"_links": {
"self": {
"href": "http://localhost:8080/api/teachers/3"
}
}
}
]
},
"_links": {
"curies": [
{
"href": "http://localhost:8080/docs/html5/{rel}.html",
"name": "school",
"templated": true
}
]
}
}

Teacher类看起来像这样:

public class Teacher {
private String name;
private String state;

// getters and setters...
}

GET 方法的 REST 服务的返回类型是 ResponseEntity<Resources<Resource<Component>>> .因此,我在客户端代码中的请求如下所示:

...
RestTemplate restTemplate = new RestTemplate();

Map<String, Object> dummy = new HashMap<>();
HttpEntity<String> httpEntity = getHttpEntity();

ResponseEntity<Resources<Resource<Teacher>>> response = restTemplate.exchange(url,
HttpMethod.GET,
httpEntity,
new ParameterizedTypeReference<Resources<Resource<Teacher>>>() {});

Resources<Resource<Teacher>> resources = response.getBody();
...

当我使用响应类型发出请求时 ParameterizedTypeReference响应内容为空。当我用 String 做的时候我检索内容列表。

我应该如何请求以响应类型 ParameterizedTypeReference 检索它将其直接映射到 POJO 中?

最佳答案

当然,你应该选择 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

关于java - 使用 spring-hateoas 使用基于 HAL 的 REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com