RestTemplate对象
RestTemplate是什么?
一个代码中的类,实现对象封装了Http协议,所以可以通过这个对象在代码中向外使用Http协议。
之前我们发送请求的方式是:
- 直接浏览器输入url地址
- js代码
- jquery
- ajax
有了RestTemplate可以法搜代码内部请求,使得某个程序如果包装了这个对象,就可以在代码执行阶段,发送http请求,形成程序之间的通信结构
如何使用
import org.junit.Test;
import org.springframework.web.client.RestTemplate;
public class RestTestRun {
/**
* 使用RestTemplate向baidu首页发送请求
*/
@Test
public void test01(){
//准备一个访问地址
String url="https://www.baidu.com";
//准备一个调用方法api的对象
RestTemplate template=new RestTemplate();
//调用对象的api发送http请求,获取对方服务器响应
String forObject = template.getForObject(url, String.class);
System.out.println(forObject);
/*
getForObject:发送一个get请求,获取响应体的内容的api方法
param:
1:url,服务器访问的url地址
2:Class,服务器响应体数据格式的类型对象
return:
根据Class类型,接收的响应体的数据
*/
}
}
/**
*
*/
@Test
public void test02(){
Long id=1l;
String url="http://www.aise.com/course";
RestTemplate template=new RestTemplate();
SystemUtil forObject = template.getForObject(url, SystemUtil.class);
System.out.println(forObject);
/**
* getforObject:可以对服务器返回响应体数据进行解析,如果是html格式文本对应的就是String类型
* 如果是json字符串,完全可以创建一个对应这个字符串的对象,解析json
*/
}
其他例子(map传递金额其他方式的传递)
@Test
public void test03(){
Long id=1l;
String url="http://www.aise.com/course/manage/major/bind?majorId="+id;
RestTemplate template=new RestTemplate();
SystemUtil forObject = template.getForObject(url, SystemUtil.class);
System.out.println(forObject);
/**
* 如果get请求,传递参数1-2个,可以在url中,拼接参数
* 但是这种方式不方便,如果是post提交,如果参数非常复杂多样,参数管理是问题,
* getForget提供了2种传递参数的方式
*/
}
/*
getforget提供可变的参数传递
*/
@Test
public void test04(){
Long id=1l;
String url="http://www.aise.com/course/manage={1}&age={2}&localtion={3}";
RestTemplate template=new RestTemplate();
SystemUtil forObject = template.getForObject(url, SystemUtil.class,id,18,"北京");
System.out.println(forObject);
/**
* getforObject:可以对服务器返回响应体数据进行解析,如果是html格式文本对应的就是String类型
* 如果是json字符串,完全可以创建一个对应这个字符串的对象,解析json
*/
}
/**
* 还提供了map对象参数传递
*/
@Test
public void test05(){
Long id=1l;
String url="http://www.aise.com/course/manage/majorId={majorId}&age={age}&localtion={localtion}";
RestTemplate template=new RestTemplate();
Map<String,Object> map=new HashMap<>();
map.put("majorId",id);
map.put("age",18);
map.put("localtion","上海");
SystemUtil forObject = template.getForObject(url, SystemUtil.class,map);
System.out.println(forObject);
}
/**
* 支持其他类型的http请求,get(查询),post(新增),put文件上传,delete(删除资源)
* head(响应状态报文
* options(问服务器,支持哪几种http请求),trace(追踪,查看请求在服务器之间传递的次数,限制传递的次数
*/
@Test
public void test06(){
Long id=1l;
String url="http://www.aise.com/course";
RestTemplate template=new RestTemplate();
SystemUtil forObject = template.getForObject(url, SystemUtil.class);
template.postForObject("",null,null);
template.put("",null);
template.exchange("", HttpMethod.TRACE, null, (Class<Object>) null);
System.out.println(forObject);
}