1. 什么是RestTemplate
传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。
2.使用方式
2.1导入依赖
<!--RestTemplate-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2.2配置RestTemplate
@Configuration
public class RestTemplateConfig {
@Autowired
private RestTemplateBuilder builder;
@Bean
public RestTemplate restTemplate(){
return builder.build();
}
}
2.3引用并使用
service层(restfull提交方式)
@Service
@Slf4j
public class RequestURLServiceImpl {
//访问地址:http://t.weather.sojson.com/api/weather/city/{city}
private static final String url = "http://t.weather.sojson.com/api/weather/city/";
@Autowired
private RestTemplate restTemplate; //此模板需要到config下配置
public String demo(String id){
String restTemplateForObject = restTemplate.getForObject(url+id, String.class);
//也可以使用下面这一行写法直接将获取的数据封装到实体类中,前提是要有相对应的实体类
// User user = restTemplate.getForObject("https://www.XXX.com/", User.class);
log.info(restTemplateForObject);
return restTemplateForObject;
}
}
controller层
@Controller
@RequestMapping("/request")
@Slf4j
public class RequestController {
@Autowired
private RequestURLServiceImpl requestURLService;
@RequestMapping("/cityid/{cityid}")
@ResponseBody
public String getWeatherResponseById( @PathVariable("cityid") String cityid){
String str = requestURLService.demo(cityid);
return str;
}
}
访问结果
3.Post提交方式
3.1环境 运行两个项目 被调用者项目端口号为8080 调用者端口号为8085
3.2被调用者:只写了一个controller如下
@RestController
public class Test {
//模拟post接口此方法将传递过来的的参数拼接然后返回
@PostMapping("/ppp")
public String p(@RequestParam("str01")String str01,@RequestParam("str02") String str02){
System.out.println("aaaaaaaaaaaaaa"+str01+str02);
return str01+str02;
}
}
3.2调用者:service代码
@Service
@Slf4j
public class RequestURLServiceImpl implements RequestURLService {
@Autowired
private RestTemplate restTemplate; //此模板需要到config下配置
public String posturl(String str01 ,String str02){
String url = "http://localhost:8080/ppp";
//若是所需参数为对象的话则将map换成实体类对象即可
MultiValueMap<String,Object> map = new LinkedMultiValueMap();
map.add("str01",str01);
map.add("str02",str02);
//返回值为String
String restTemplateForObject = restTemplate.postForObject(url,map,String.class);
return restTemplateForObject;
}
}
3.2调用者:controller代码
@Controller
@RequestMapping("/request")
@Slf4j
public class RequestController {
@PostMapping("/post")
@ResponseBody
public String posturl( String str01,String str02){
String str = requestURLService.posturl(str01, str02);
return str;
}
}
3.3测试结果