Spring RESTFul Client – RestTemplate Example--转载
原文地址:http://howtodoinjava.com/2015/02/20/spring-restful-client-resttemplate-example/
After learning to build Spring REST based RESTFul APIs for XML representation and JSON representation, let’s build a RESTFul client to consume APIs which we have written. Accessing a third-party REST service inside a Spring application revolves around the use of the Spring RestTemplate class. The RestTemplate class is designed on the same principles as the many other Spring *Template classes (e.g., JdbcTemplate, JmsTemplate ), providing a simplified approach with default behaviors for performing complex tasks.
Given that the RestTemplate class is designed to call REST services, it should come as no surprise that its main methods are closely tied to REST’s underpinnings, which are the HTTP protocol’s methods: HEAD, GET, POST, PUT, DELETE, and OPTIONS. E.g. it’s methods are headForHeaders(), getForObject(), postForObject(), put()and delete() etc.
Read More and Source Code : Spring REST JSON Example
HTTP GET Method Example
1) Get XML representation of employees collection in String format
REST API Code
|
1
2
3
4
5
6
|
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)public String getAllEmployeesXML(Model model){ model.addAttribute("employees", getEmployeesCollection()); return "xmlTemplate";} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
|
private static void getEmployees(){ RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); System.out.println(result);} |
2) Get JSON representation of employees collection in String format
REST API Code
|
1
2
3
4
5
6
|
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)public String getAllEmployeesJSON(Model model){ model.addAttribute("employees", getEmployeesCollection()); return "jsonTemplate";} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
|
private static void getEmployees(){ RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); System.out.println(result);} |
3) Using custom HTTP Headers with RestTemplate
REST API Code
|
1
2
3
4
5
6
|
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)public String getAllEmployeesJSON(Model model){ model.addAttribute("employees", getEmployeesCollection()); return "jsonTemplate";} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
private static void getEmployees(){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class); System.out.println(result);} |
4) Get data as mapped object
REST API Code
|
1
2
3
4
5
6
|
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)public String getAllEmployeesXML(Model model){ model.addAttribute("employees", getEmployeesCollection()); return "xmlTemplate";} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
|
private static void getEmployees(){ RestTemplate restTemplate = new RestTemplate(); EmployeeListVO result = restTemplate.getForObject(uri, EmployeeListVO.class); System.out.println(result);} |
5) Passing parameters in URL
REST API Code
|
1
2
3
4
5
6
7
8
9
|
@RequestMapping(value = "/employees/{id}")public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") int id){ if (id <= 3) { EmployeeVO employee = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com"); return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK); } return new ResponseEntity(HttpStatus.NOT_FOUND);} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
10
11
12
|
private static void getEmployeeById(){ Map<String, String> params = new HashMap<String, String>(); params.put("id", "1"); RestTemplate restTemplate = new RestTemplate(); EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class, params); System.out.println(result);} |
HTTP POST Method Example
REST API Code
|
1
2
3
4
5
6
|
@RequestMapping(value = "/employees", method = RequestMethod.POST)public ResponseEntity<String> createEmployee(@RequestBody EmployeeVO employee){ System.out.println(employee); return new ResponseEntity(HttpStatus.CREATED);} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
10
11
|
private static void createEmployee(){ EmployeeVO newEmployee = new EmployeeVO(-1, "Adam", "Gilly", "test@email.com"); RestTemplate restTemplate = new RestTemplate(); EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class); System.out.println(result);} |
HTTP PUT Method Example
REST API Code
|
1
2
3
4
5
6
7
|
@RequestMapping(value = "/employees/{id}", method = RequestMethod.PUT)public ResponseEntity<EmployeeVO> updateEmployee(@PathVariable("id") int id, @RequestBody EmployeeVO employee){ System.out.println(id); System.out.println(employee); return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
10
11
12
|
private static void deleteEmployee(){ Map<String, String> params = new HashMap<String, String>(); params.put("id", "2"); EmployeeVO updatedEmployee = new EmployeeVO(2, "New Name", "Gilly", "test@email.com"); RestTemplate restTemplate = new RestTemplate(); restTemplate.put ( uri, updatedEmployee, params);} |
HTTP DELETE Method Example
REST API Code
|
1
2
3
4
5
6
|
@RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)public ResponseEntity<String> updateEmployee(@PathVariable("id") int id){ System.out.println(id); return new ResponseEntity(HttpStatus.OK);} |
REST Client Code
|
1
2
3
4
5
6
7
8
9
10
|
private static void deleteEmployee(){ Map<String, String> params = new HashMap<String, String>(); params.put("id", "2"); RestTemplate restTemplate = new RestTemplate(); restTemplate.delete ( uri, params );} |
Let me know if something needs more explanation.
Happy Learning !!
Spring RESTFul Client – RestTemplate Example--转载的更多相关文章
- Spring Cloud ZooKeeper集成Feign的坑1,错误:Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
错误如下: ERROR 31473 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** A ...
- spring boot 注入 restTemplate
转载自:http://blog.csdn.net/liuchuanhong1/article/details/54631080 package com.chhliu.springboot.restfu ...
- Java-Class-C:org.springframework.web.client.RestTemplate
ylbtech-Java-Class-C:org.springframework.web.client.RestTemplate 1.返回顶部 1. org.springframework.web.c ...
- 测试必须学spring RESTful Service(上)
文末我会说说为什么测试必须学spring. REST REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful, 看url就知道要什么 看met ...
- spring中context:property-placeholder/元素 转载
spring中context:property-placeholder/元素 转载 1.有些参数在某些阶段中是常量 比如 :a.在开发阶段我们连接数据库时的连接url,username,passwo ...
- Spring Boot使用RestTemplate消费REST服务的几个问题记录
我们可以通过Spring Boot快速开发REST接口,同时也可能需要在实现接口的过程中,通过Spring Boot调用内外部REST接口完成业务逻辑. 在Spring Boot中,调用REST Ap ...
- C# 客户端篇之实现Restful Client开发(RestSharp帮助类)
上篇文章<C# 服务端篇之实现RestFul Service开发(简单实用)>讲解到,如果开发一个简单的Restful风格的Service,也提到了简单创建一个Restful Client ...
- 使用 Spring 提供的 restTemplate 完成 Http 服务消费
RestTemplate 介绍 RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程 Http 服务的方法,能够大大提高 ...
- Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration
https://www.cnblogs.com/EasonJim/p/7546136.html 错误如下: ERROR 31473 --- [ main] o.s.b.d.LoggingFailure ...
随机推荐
- js运动 摩擦运动
<!DOCTYPE HTML> <HTML> <meta http-equiv="Content-Type" content="text/h ...
- 前端复习-01-dom操作包括ie和现代浏览器处理相关
一.事件流事件流描述的是从页面中接受事件的顺序.IE的事件流是事件冒泡流,而Netscape的事件流是事件捕获流1.事件冒泡事件冒泡,即事件最开始由最具体的元素(文档中嵌套层次最深的那个节点)接收,然 ...
- Mac下安装eclipse+python+pydev+numpy+matplotlib
*本人亲测是成功的安装过程 1.更新Mac系统默认低版本的python2.7.请参见这篇文章:http://jingyan.baidu.com/article/14bd256e39b63dbb6d26 ...
- MyEclipse中消除frame引起的“the file XXX can not be found.Please check the location and try again.”的错误
读者如要转载,请标明出处和作者名,谢谢. 地址01:http://space.itpub.net/25851087 地址02:http://www.cnblogs.com/zjrodger/ 作者名: ...
- Could not find a transformer to transform "SimpleDataType{type=org.mule.transport.NullPayload
mule esb报错 com.isoftstone.esb.transformer.Json2RequestBusinessObject.transformMessage(Json2RequestBu ...
- ADT-bundle
eclipse 弹出 Version 1.4.2_03 of the JVM not suitable for this product.Version1.6or geeater is requir ...
- Win7 SP1语言包微软官方下载地址及使用方法 2
情形一:如果您的系统版本是企业版.旗舰版,可以在Windows update中检测语言包按照提示下载安装即可.如果觉得Windows update不方便的话,可以在本文第二部分中下载所需的语言包,下载 ...
- ASP.NET验证控件RegularExpressionValidator的常见表达式
可以输入非0和0开头的数字:“^(0*[1-9][0-9]*|[1-9][0-9]*)$”只能输入数字:“^[0-9]*$”只能输入n位的数字:“^\d{n}$”只能输入至少n位数字:“^\d{n,} ...
- WPF的DataGrid绑定ItemsSource后第一次加载数据有个别列移位的解决办法
最近用WPF的DataGrid的时候,发现一个很弱智的问题,DataGrid的ItemsSource是绑定了一个属性: 然后取数给这个集合赋值的时候,第一次赋值,就会出现列移位 起初还以为是显卡的问题 ...
- Ehcache(05)——缓存的查询
http://haohaoxuexi.iteye.com/blog/2117505 缓存的查询 目录 1. 使Cache可查询 1.1 基于Xml配置 1.2 基于代码的配置 2 ...