原文地址: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()
{
     
    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()
{
    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()
{
 
    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 !!

Spring RESTFul Client – RestTemplate Example--转载的更多相关文章

  1. 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 ...

  2. spring boot 注入 restTemplate

    转载自:http://blog.csdn.net/liuchuanhong1/article/details/54631080 package com.chhliu.springboot.restfu ...

  3. Java-Class-C:org.springframework.web.client.RestTemplate

    ylbtech-Java-Class-C:org.springframework.web.client.RestTemplate 1.返回顶部 1. org.springframework.web.c ...

  4. 测试必须学spring RESTful Service(上)

    文末我会说说为什么测试必须学spring. REST REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful, 看url就知道要什么 看met ...

  5. spring中context:property-placeholder/元素 转载

    spring中context:property-placeholder/元素  转载 1.有些参数在某些阶段中是常量 比如 :a.在开发阶段我们连接数据库时的连接url,username,passwo ...

  6. Spring Boot使用RestTemplate消费REST服务的几个问题记录

    我们可以通过Spring Boot快速开发REST接口,同时也可能需要在实现接口的过程中,通过Spring Boot调用内外部REST接口完成业务逻辑. 在Spring Boot中,调用REST Ap ...

  7. C# 客户端篇之实现Restful Client开发(RestSharp帮助类)

    上篇文章<C# 服务端篇之实现RestFul Service开发(简单实用)>讲解到,如果开发一个简单的Restful风格的Service,也提到了简单创建一个Restful Client ...

  8. 使用 Spring 提供的 restTemplate 完成 Http 服务消费

    RestTemplate 介绍 RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程 Http 服务的方法,能够大大提高 ...

  9. 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 ...

随机推荐

  1. 如何注册AWS Global账号

    去年底AWS宣布落地中国以来,可能很多童鞋都在热切地等待试用AWS中国的服务.但是AWS中国目前还在犹抱琵琶半遮面,没有完全向大家开放.不过,大家也不必干等待.要是真感兴趣的话可以自己或者让公司先注册 ...

  2. java 编写hadoop程序中使用第三方libxx.so库

    在使用java编写hadoop处理程序时遇到了,java使用依赖的第三方libxx.so库的情况,找到了一种可行的方法,记录一下,希望对别人也有帮助: 加入需要使用的lib库为libxxx.so 1. ...

  3. linux rar工具

    rar系统工具: wget http://www.rarlab.com/rar/rarlinux-3.8.0.tar.gz tar -zxvf rarlinux-3.8.0.tar.gz cd rar ...

  4. China特色创新现状

    1,unity桌面 2,http://www.cs2c.com.cn/ 3,http://os.51cto.com/art/200602/20350.htm 4,http://zhidao.baidu ...

  5. 【多线程】Java线程面试题 Top 50(转载)

    Java线程面试题 Top 50 原文链接:http://www.importnew.com/12773.html   本文由 ImportNew - 李 广 翻译自 javarevisited.欢迎 ...

  6. Chocolatey的安装与使用

    @(编程) 前言 在 Linux 下,大家喜欢用 apt-get 来安装应用程序,如今在 windows 下,大家可以使用 Chocolatey 来快速下载搭建一个开发环境. Chocolatey 的 ...

  7. HDU4289Control(最大流)

    看了这道题,然后重新开始练习自己的刚敲不久的网络流,发现还是难以一遍敲得完整啊,,,,, 调了...遍,改了...遍,测了...遍,交了,,,遍,总算是A了,,不简单啊 然后试着用了其他两种算法EK和 ...

  8. 开机自动播放音乐的vbs

    今天无意间看到了vbs这小玩意,就突发奇想,自学了一下,倒弄出如下的小玩意,大牛勿喷!这个可用做撩妹神技也可以用于提醒自己!使用方法:复制程序到txt文本里面保存,然后改后缀为vbs,丢到C:\Pro ...

  9. 获取和设置localStorage

    东钿金融服务平台 用户第一次访问页面出现,引导步骤,起初一直使用cookie,但是cookie一直不稳定 今天老大说改用localStorage 于是乎百度,查了一篇博客 http://www.cnb ...

  10. Linux之sed,awk(流编辑器)

    sed:  s----substitute(替换) 1. 文本替换(使用-i选项,可以将结果应用于原文件) many people在进行替换之后,借助重定向来保存文件(未使用-i选项): $ sed  ...