zoukankan      html  css  js  c++  java
  • 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., 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 !!

  • 相关阅读:
    手机号码正则,座机正则,400正则
    Win10 开始运行不保存历史记录原因和解决方法
    Ubuntu 普通用户无法启动Google chrome
    在win10 64位系统安装 lxml (Python 3.5)
    SecureCRT窗口输出代码关键字高亮设置
    【转】win2008 中iis7设置404页面但返回状态200的问题解决办法
    ionic app开发遇到的问题
    Ubuntu 创建文件夹快捷方式
    Ubuntu配置PATH环境变量
    Ubuntu 升级python到3.7
  • 原文地址:https://www.cnblogs.com/davidwang456/p/4552018.html
Copyright © 2011-2022 走看看