码迷,mamicode.com
首页 > 编程语言 > 详细

java之RestTemplate的访问应用

时间:2018-01-09 12:57:29      阅读:372      评论:0      收藏:0      [点我收藏+]

标签:开发   linked   soa   encode   html   link   设置   string   http请求   

  一、REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。

  目前在三种主流的Web服务实现方案中,因为REST模式的Web服务与复杂的SOAP和XML-RPC对比来讲明显的更加简洁,越来越多的web服务开始采用REST风格设计和实现。例如,Amazon.com提供接近REST风格的Web服务进行图书查找;雅虎提供的Web服务也是REST风格的。
  二、RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
  三、这里主要介绍几种RestTemplate的用法
  1)第一种post请求
  public ResponseEntity doPost(String url, Map<String,Object> map) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Gson gson = new Gson();
        HttpEntity<String> httpEntity = new HttpEntity(gson.toJson(map), httpHeaders);
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Object.class);
        return responseEntity;
    }

  说明:这种方式主要是用于post数据的传输,因为rest的简洁性,在使用上面也会得到恨到的应用。

  2)第二种get请求

   public ResponseEntity doGet(String url) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.TEXT_HTML);
        HttpEntity<String> httpEntity = new HttpEntity(httpHeaders);
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class);
        return responseEntity;
    }

  说明:get请求没有太大的解释,基本上面的设置都是这样

  3)第三种from方式

  public ResponseEntity doFrom(String url, LinkedMultiValueMap<String, Object> map) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> httpEntity = new HttpEntity(httpHeaders);
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Object.class);
        return responseEntity;
    }

  说明:表单的方式使用虽然不常见,但是应用的时候也需要注意几点,数据形式LinkedMultiValueMap和HashMap不同存储方式的是name=rest&password=123。

  而Content-Type的方式为application/x-www-form-urlencoded。这种表单处理方式,对于数据的处理上面要特别注意

 

 

java之RestTemplate的访问应用

标签:开发   linked   soa   encode   html   link   设置   string   http请求   

原文地址:https://www.cnblogs.com/ll409546297/p/8250794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!