一、restTemplate的引入 当前项目里对外暴露的接口基本都是一个rest的api,与其他项目对接时,通常也是调用对方暴露出来的rest api【http的接口】。这就涉及到要在自己项目里发送http请求。 调用http请求的方式:可以自己使用httpclient或者其他原生方式构建http请求。spring当然也提供了调用模板,那就是restTemplate。本文就是罗列restTemplate的调用及不同的传参方式。
spring中引入(引入就由spring托管了。直接@Autowired注解引用就行)
spring-config.xml配置文件中添加
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"></bean>
springboot中引入
在启动类 XXXApp.java 中添加:
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
使用时,@Autowired注解引入
二、使用 //1.请求头 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8")); httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
//2.请求体 HttpEntity<Map<String, Object>> httpEntityEmpty = new HttpEntity<>(null, httpHeaders);
请求体new对象中可以是两个参数 第一个为请求体 httpBody
//3.响应体 ResponseEntity<Map> responseEntity = restTemplate.exchange(urlToQueryAllPeopleGet+"?visit_token="+v, HttpMethod.GET, httpEntityEmpty,Map.class);