RestFul APi 介绍
-
(1)REST 是什么?
Representational State Transfer 直接翻译:表现层状态转移 -
(2)到底是什么?
URL定位资源,用HTTP动词(GET,POST,DELETE,PUT)描述操作。
-
(3)有什么用?
REST描述的是在网络中client和server的一种交互形式;REST本身不实用,实用的是如何设计 RESTful API(REST风格的网络接口); -
(4)Server提供的RESTful API中,URL中只使用名词来指定资源,原则上不使用动词。“资源”是REST架构或者说整个网络处理的核心
Rest介绍
- (1) 用HTTP协议里的动词来实现资源的添加,修改,删除等操作。即通过HTTP动词来实现资源的状态扭转
- (2)动作
GET 用来获取资源,
POST 用来新建资源(也可以用于更新资源),
PUT 用来更新资源,
DELETE 用来删除资源
看Url就知道要什么
看http method就知道干什么
看http status code就知道结果如何
@RestController
@Slf4j
public class UserController {
//普通的地址表示方式
@RequestMapping(path = "/users/find.do", method = {RequestMethod.GET})
public Object find(int id) {//
//到数据库中查询模拟
User user = new User();
user.setId(id);
user.setUasername("jack");
user.setPassword("123456");
return user;
}
//restful
//
//user/2
//1:占位符 /user/{id}
//2:取path上的值 user/1 使用注解来取
@RequestMapping(path = "/users/{id}", method = {RequestMethod.GET})
public Object get(@PathVariable("id") int userId) {//@PathVariable取得值 1 赋值给与占位符变量的同名
//到数据库中查询模拟
log.info("get id "+userId);
User user = new User();
user.setId(userId);
user.setUasername("jack");
user.setPassword("123456");
return user;
}
@RequestMapping(path = "/users/{id}", method = {RequestMethod.DELETE})
public Object delete(@PathVariable int id) {
//到数据库中查询模拟
log.info("删除了 id "+id);
User user = new User();
user.setId(id);
user.setUasername("jack");
user.setPassword("123456");
return user;
}
}
postman
RestTemplate介绍
- (1)一般情况下有如下三种http客户端工具类包都可以方便的进行http服务调用
- httpClient
apache
- okHttp
- JDK原生URLConnection
java
- (2)RestTemplate是什么?
spring 提供了RestTemplate的工具类
对上述的3种http客户端工具类进行了封装,可在spring项目中使用RestTemplate进行服务调用。
请求地址 + 请求方式
请求参数
返回值 - (3)RestTemplate有什么用?
类似postman 可以模拟 http请求 ,get,post,delete,put
RestTemplate介绍
- (1)常用方法列表
- (2)RestTemplate有什么特点?
使用restTemplate访问restful接口非常的简单粗暴无脑。
postForObject(url, requestMap, ResponseBean.class)
参1 请求地址
参2 请求参数
参3 HTTP响应转换被转换成的对象类型
@SpringBootTest
class Demo02restTemplateApplicationTests {
@Test
void test01() {
RestTemplate template = new RestTemplate();
//发送delete请求
template.delete("http://localhost:8080/user/10");
}
//还可以将返回的json数据直接转换成java对象
@Test
void test02() {
RestTemplate template = new RestTemplate();
//发送get请求
User user=template.getForObject("http://localhost:8080/user/10", User.class);
System.out.println(user);
}
}