[英]Programming a REST client - is there a framework similar to Axis/JAX-WS for SOAP
现在,我正在学习如何构建REST Web服务-我正在尝试构建一个通过XML(而非JSON)进行通信的REST服务。
我在这里使用教程。 http://www.vogella.com/tutorials/REST/article.html
我创建了一个GET API,该API返回待办事项列表
@GET
@Produces({ MediaType.TEXT_XML })
public List<ToDo> getXML()
{
ArrayList<ToDo> al = new ArrayList<ToDo>();
ToDo t = new ToDo();
t.setSummary("First ToDo");
t.setDescription("This is my first ToDo");
al.add(t);
t.setSummary("2nd Todo");
t.setDescription("This is my 2nd Todo");
al.add(t);
return al;
}
我有一个调用此方法的客户端程序
String xmlAnswer =
target.path("rest").path("hello").request().accept(MediaType.TEXT_XML).get(String.class);
我得到以下回应
<?xml version="1.0" encoding="UTF-8" standalone="yes">
<toDoes>
<toDo>
<description>This is my 2nd Todo</description>
<summary>2nd Todo</summary>
</toDo>
<toDo>
<description>This is my 2nd Todo</description>
<summary>2nd Todo</summary></toDo>
</toDoes>
</toDoes>
但是,我确信有一种对客户端进行编程的简便方法-我想获取一个ToDo对象数组而不是XML。 我该怎么做呢? 如何为客户端ToDo类生成存根?如何以ToDo对象数组的形式获取答案?
您可以使用Spring-web API来调用REST服务。
将Spring-web添加到您的类路径,然后使用以下代码:
List<MyBean> beans = null;
RestTemplate template = new RestTemplate()
ParameterizedTypeReference<List<MyBean>> responseType = new ParameterizedTypeReference<List<MyBean>>() {};
Object requestParm = null;
ResponseEntity<List<MyBean>> response = template.exchange("http://example.com",HttpMethod.GET, requestParm, responseType);
if(response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
beans = response.getBody();
}
根据@peeskillet的评论,这就是我所做的。
我获取了输出XML-使用http://xmlgrid.net/xml2xsd.html从中创建XSD-然后使用xjc
生成ToDoes类
ToDoes tds = target.path("rest").path("hello").request()
.accept(MediaType.TEXT_XML).get(ToDoes.class);
List<ToDoes.ToDo> l = tds.getToDo() ;
for (int i = 0; i < l.size(); ++i)
{
System.out.println( "Summary"+i+":" + l.get(i).getSummary());
System.out.println( "Summary"+i+":" + l.get(i).getDescription());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.