一、REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。
目前在三种主流的Web服务实现方案中,因为REST模式的Web服务与复杂的SOAP和 -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, > 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, .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, .class); return responseEntity; }
说明:get请求没有太大的解释,基本上面的设置都是这样
3)第三种from方式
public ResponseEntity doFrom(String url, edMultiValueMap<String, > 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, .class); return responseEntity; }
说明:表单的方式使用虽然不常见,但是应用的时候也需要注意几点,数据形式 edMultiValueMap和HashMap不同存储方式的是name=rest&password=123。
而Content-Type的方式为application/x-www-form-urlencoded。这种表单处理方式,对于数据的处理上面要特别注意
继续阅读与本文标签相同的文章
上一篇 :
Linux工具之Vim编辑器
下一篇 :
Linux命令之scp、ssh
-
DNS服务-了解篇
2026-05-26栏目: 教程
-
cobbler 无人值守-安装
2026-05-26栏目: 教程
-
cobbler 无人值守-介绍
2026-05-26栏目: 教程
-
PXE自动化安装系统
2026-05-26栏目: 教程
-
制作iso镜像U盘自动化安装linux系统
2026-05-26栏目: 教程
