RestTemplate
是什么
为HTTP请求/响应提供了一种模板,简化编写
常用方法
经常把RestTemplate作为一个bean使用,在业务中直接注入就可以使用,一般有get请求、post请求和普适请求(exchange)
- restTemplate.getForEntity(url,String.class)
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
String body = responseEntity.getBody();
System.out.println(body);
- restTemplate.postForEntity(url,request)
notice: request参数一般是HttpEntity对象
一般格式为HttpEntity(请求体,请求头)
请求头的创建方法:
HttpHeaders httpHeaders = new HttpHeader();
httpHeaders.set("xx","xx");
请求体一定要使用MultiValueMap类型:
MultiValueMap<String,Stirng> map = new MultivalueMap<>();
map.add("参数名","xxx");
然后将上面这两项封装到HttpEntity中
HttpEntity request = new HttpEntity(map,httpHeaders);
restTemplate.postForEntity("www.xxx.com",request);
最后返回的是一个ResponseEntity<T>
- 最常用:restTemplate.exchange(url,HttpMethod,request,responseType)
可自定义请求,比较常用
HttpMehod: GET POST PUT DELETE等
request: 请求实体=请求头+请求体 具体封装方法如上
responseType: 返回类型,对一般网页是String.class
具体实例:
String url = "http://xxxx.com";
// 设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
//设置user-agent 模拟浏览器访问
httpHeaders.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
//设置content-type为form-data
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//使用MultiValueMap封装请求体
MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
map.add("name","xxxx");
// 创建http请求实体
HttpEntity request = new HttpEntity(map,httpHeaders);
//获取响应实体
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST,request,String.class);
return responseEntity.getBody();