问题:我们在使用了rpc和feign之后很少用到调用别人接口,但是总有那么不合群的不用我们伟大的springboot,这时候调用别人的接口就需要RestTemplate。
1.并不需要引入meaven包,因为springboot集成了
2.调用分为get和post请求,我们分开讲
2.1首先get请求,直接上代码
String url ="http://baidu.com";
//新建一个对象
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();//为了防止需要一些数据放到请求头的
HttpMethod method = HttpMethod.GET;
// 提交方式,以json的方式提交
headers.setContentType(MediaType.APPLICATION_JSON);
Params params=geturlToken();//获取token
String token=params.getToken();
//设置请求头的数据
headers.add("x-device-id", "**");
headers.add("Authorization", "Bearer " + token);
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(null, headers);
//执行HTTP请求,将返回的结构使用String 类格式化,response 就是返回的数据
ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
2.2post请求带参数,参数为json格式
String url="http://baidu";
String token="";
RestTemplate restTemplate = new RestTemplate();
//设置Http Header
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;//设置请求方式为post请求
//设置请求媒体数据类型我这个不需要
//headers.setContentType(MediaType.APPLICATION_JSON);
//添加在请求头上的数据
headers.add("x-device-id", "**");
//设置返回媒体数据类型
// headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//设置参数
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("mobile"," aaa");
map.add("password","aaa");
map.add("nation_code","86");
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, String>> formEntity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
//执行HTTP请求,将返回的结构使用String 类格式化
ResponseEntity<String> response = restTemplate.exchange(url, method, formEntity, String.class);
String jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("res").getString("token");