首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务(5)

使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务(5)

使用 RestTemplate 与 REST 服务进行通信“使用 Spring 3 构建 RESTful web 服务”(参见 )介绍了如何使用 CURL 和 REST 客户端测试 REST 服务。从编程水平上讲,Jakarta Commons HttpClient 通常用于完成此测试(但这不在本文的讨论范围中)。您还可以使用名为 RestTemplate 的 Spring REST 客户端。从概念上讲,它与 Spring 中的其他模板类相似,比如 JdbcTemplate 和 JmsTemplate。
RestTemplate 还使用 HttpMessageConverter。您可以将对象类传入请求并使转换程序处理映射。
配置 RestTemplate清单 10 显示了 RestTemplate 的配置。它还使用之前介绍的 3 个转换程序。
清单 10. 配置 RestTemplate
1
2
3
4
5
6
7
8
9
10
<bean id="restTemplate"
class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
    <list>
    <ref bean="marshallingConverter" />
    <ref bean="atomConverter"  />
    <ref bean="jsonConverter" />
    </list>
</property>
</bean>




本文中的示例仅使用了一些可简化服务器之间通信的方法。RestTemplate支持其他方法,包括:
  • exchange:使用请求正文执行一些 HTTP 方法并获得响应。
  • getForObject:执行 HTTP GET 方法并将响应作为对象获得。
  • postForObject:使用特定请求正文执行 HTTP POST 方法。
  • put:使用特定请求正文执行 HTTP PUT 方法。
  • delete:执行 HTTP DELETE方法以获得特定 URI。
代码示例下列代码示例帮助阐述如何使用 RestTemplate。参见 RestTemplate API(参见 )获得使用的 API 的详细说明。
清单 11 显示如何将头添加到请求中,然后调用请求。使用 MarshallingHttpMessageConverter 您可以获得响应并将其转换为类型类。可以使用不同的媒体类型测试其他具象。
清单 11. XML 具象请求
1
2
3
4
5
6
7
8
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<EmployeeList> response = restTemplate.exchange(
"http://localhost:8080/rest/service/emps",
HttpMethod.GET, entity, EmployeeList.class);
EmployeeListingemployees = response.getBody();
// handle the employees




清单 12 显示了如何将新员工发布到服务器。服务器端服务 addEmp() 可接受媒体类型为 application/xml 和 application/json 的数据。
清单 12. 发布新员工
1
2
3
4
5
6
Employee newEmp = new Employee(99, "guest", "guest@ibm.com");
HttpEntity<Employee> entity = new HttpEntity<Employee>(newEmp);
ResponseEntity<Employee> response = restTemplate.postForEntity(
"http://localhost:8080/rest/service/emp", entity, Employee.class);
Employee e = response.getBody();
// handle the employee




清单 13 显示了如何 PUT 修改的员工以更新旧员工。它还显示了可用作请求 URI 占位符({id})的功能。
清单 13. PUT 以更新员工
1
2
3
4
Employee newEmp = new Employee(99, "guest99", "guest99@ibm.com");
HttpEntity<Employee> entity = new HttpEntity<Employee>(newEmp);
restTemplate.put(
    "http://localhost:8080/rest/service/emp/{id}", entity, "99");




清单 14 显示了如何 DELETE 现有员工。
清单 14. DELETE 现有员工
1
2
restTemplate.delete(
    "http://localhost:8080/rest/service/emp/{id}", "99");

返回列表