原文地址: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., JdbcTemplateJmsTemplate ), 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()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";
     
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees.json";
     
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees";
     
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees";
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees/{id}";
     
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees";
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees/{id}";
     
    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()
{
    final String uri = "http://localhost:8080/springrestexample/employees/{id}";
     
    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 !!

转载于:https://www.cnblogs.com/davidwang456/p/4552018.html

Spring RESTFul Client – RestTemplate Example--转载相关推荐

  1. RESTful Web Services in Spring 3(下)转载

    上一篇我主要发了RESTful Web Services in Spring 3的服务端代码,这里我准备写客户端的代码. 上篇得连接地址为:http://yangjizhong.iteye.com/b ...

  2. Spring Restful Web服务示例 - 使用JSON/Jackson和客户端程序

    Spring Restful Web服务示例 - 使用JSON/Jackson和客户端程序 Spring是最广泛使用的Java EE框架之一.我们之前已经看到了如何使用Spring MVC来创建基于J ...

  3. Spring Restful Web服务示例 - 使用JSON,Jackson和客户端程序

    Spring Restful Web服务示例 - 使用JSON,Jackson和客户端程序 Spring是最广泛使用的Java EE框架之一.我们之前已经看到了如何使用Spring MVC来创建基于J ...

  4. spring boot(5)---RestTemplate请求HTTP(1)

    RestTemplate请求HTTP(1) 说明 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单 ...

  5. java rest 调用_Java调用Restful之RestTemplate

    1.spring-mvc.xml中增加RestTemplate的配置 2.引入相关jar包 httpclient-4.3.3.jar.httpcore-4.3.2.jar,jar包版本根据需求自行调整 ...

  6. maven集成spring_Maven集成测试和Spring Restful Services

    maven集成spring 介绍 我的原始博客通过一个非常简单的示例展示了如何分离Maven单元和集成测试. http://johndobie.blogspot.com/2011/06/seperat ...

  7. Maven集成测试和Spring Restful Services

    介绍 我的原始博客通过一个非常简单的示例展示了如何分离Maven单元和集成测试. http://johndobie.blogspot.com/2011/06/seperating-maven-unit ...

  8. Spring AOP详解(转载)所需要的包

    上一篇文章中,<Spring Aop详解(转载)>里的代码都可以运行,只是包比较多,中间缺少了几个相应的包,根据报错,几经百度搜索,终于补全了所有包. 截图如下: 在主测试类里面,有人怀疑 ...

  9. Spring WebClient vs. RestTemplate

    点击蓝色"程序猿DD"关注我 回复"资源"获取独家整理的学习资料! 1. 简介 本教程中,我们将对比 Spring 的两种 Web 客户端实现 -- RestT ...

最新文章

  1. 【 C 】最容易误判的优先级问题
  2. 如何创建自己的docker image并上传到DockerHub上
  3. .jQuery文档分析4-文档处理
  4. 【Python-ML】神经网络激励函数-Sigmoid
  5. 函数注意事项和细节讨论
  6. Indian Scientists Design Device to Collect Solar Energy 印度科学家设计太阳能收集设备
  7. WPF实现统计图(饼图仿LiveCharts)
  8. mysql表单查询_MySQL表单集合查询
  9. 利用ECG关于HRV分析
  10. Python输入和输出
  11. 诺基亚x6升级android9体验,诺基亚X6手机怎么样?诺基亚X6全面详细评测
  12. dd: 写入‘/EMPTY‘ 出错: 设备上没有空间
  13. iOS通过ASIHTTPRequest提交JSON数据
  14. 玩客云服务器怎么卖,玩客云使用教程;低价NAS怎么打造;玩客云现在还值得入手吗?-聚超值...
  15. Vue源码系列(一):Vue源码解读的正确姿势
  16. 德乐Derler T-1series 120G SSD固态硬盘不认盘修复/开卡一例(SM2258XT主控),SM2259XT2可参考
  17. Java随笔记录第二章:输入输出流程控制
  18. 玉米社:SEM竞价推广预算设置方法
  19. atitit 音频 项目 系列功能表 音乐 v3 t67.docx Atitit 音频 项目 系列功能表 音频 音乐 语言领域的功能表 听歌识曲功能 酷我功能。 铃声 功能。。 音频切割(按照副歌部
  20. 人工神经网络的算法原理,深度神经网络算法原理

热门文章

  1. java从键盘输入数据斐波那契数_从键盘输入一个正整数n,打印出斐波那契数列的前n个元素...
  2. 目前有量子计算机,中国“祖冲之”刚刚成为当前最强大的量子计算机
  3. hive数据库numeric_hive支持sql大全(收藏版)
  4. java spring上传_SpringMVC上传文件的三种方式
  5. 为客户端加入输入线程
  6. Andriod:安卓线程实现页面的自动跳转
  7. ping 超时时间_华为交换机ping命令详解
  8. C++基本序列式容器效率比较
  9. python os.system执行shell 命令
  10. 循环神经网络的数据预处理