【发布时间】:2015-01-02 14:16:56
【问题描述】:
我有两个应用程序,一个叫做 bar,它为我提供 HAL 格式的资源。另一个是 bcm 来使用该服务。
响应示例 bar 如下所示:
[
{
"name":"Brenner/in",
"_links":{
"self":{
"href":"..host/bbsng-app-rest/betrieb/15"
}
}
},
{
"name":"Dienstleistungshelfer/in HW",
"_links":{
"self":{
"href":"..host/bbsng-app-rest/betrieb/4"
}
}
},
{
...
现在我尝试使用 Spring RestTemplate 从 bcm 消耗它。我的解决方案有效,但不知何故我对该解决方案不满意,我想有一种更干净的方法。
我的客户端代码消费 RestService 看起来像:
@Autowired private RestTemplate template;
@Override
@SuppressWarnings("unchecked")
public BerufListe findeAlleBerufe() {
final BerufListe berufListe = new BerufListe();
final ResponseEntity<List> entity = template.getForEntity(LinkUtils.findBeruf(), List.class);
if (OK.equals(entity.getStatusCode())) {
final List<LinkedHashMap> body = entity.getBody();
for (final LinkedHashMap map : body) {
final LinkedHashMap idMap = (LinkedHashMap) map.get("_links");
String id = remove(String.valueOf(idMap.get("self")), "href=");
id = remove(id, "{");
id = remove(id, "}");
final String name = String.valueOf(map.get("name"));
final Beruf beruf = new Beruf(id, name);
berufListe.add(beruf);
}
}
return berufListe;
}
如您所见,几乎没有丑陋的代码。其中之一是,我的收藏没有任何泛型。另一点,我得到的 Resource_ID 非常复杂,我多次使用 StringUtils.remove 来提取 self url。
我相信 Spring 肯定有更方便的方式来使用 HAL-Response。
谢谢。
【问题讨论】:
标签: java client resttemplate spring-hateoas hal