1.Spring提供的RestTemplate
1.将RestTemplate注入到Spring容器
@SpringBootApplication
public class OrderserviceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderserviceApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2.get请求对应getForEntity,post请求对应postForEntity。传入参数url(请求路径),默认返回Json数据格式,指定封装类型后会自动封装。
@Component
public class test {
@Autowired
private RestTemplate restTemplate;
public void test() {
String url = "http://www.baidu.com";
User user = restTemplate.getForEntity(url, User.class).getBody();
}
}