@Test
void contextLoads() {
//使用RestTemplate主动发送HttpGET请求
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Video> video1 = restTemplate.getForEntity("http://www.baidu,com", Video.class);
System.out.println(video1);
//URL参数可以使用restful风格,当然也可以直接的URL参数拼接执行
ResponseEntity<Video> video2 = restTemplate.getForEntity("http://www.baidu,com/{1}/{2}", Video.class, 1, 2);
System.out.println(video2);
//高级一点的写法
Map<String,String> map = new HashMap();
map.put("start","1");
map.put("page","5");
Video video3 = restTemplate.getForObject("http://www.baidu,com/", Video.class, map);
//getForObject()其实比getForEntity()多包含了将HTTP转成POJO的功能,但是getForObject没有处理response的能力。
// 因为它拿到手的就是成型的pojo。省略了很多response的信息。如果需要转换成pojo,还需要json工具类的引入。
//======================================================================================================
//使用RestTemplate主动发送HttpPOST请求
String url = "http://www.baidu.com";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map1= new LinkedMultiValueMap<>();
map1.add("email", "844072586@qq.com");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map1, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
System.out.println(response.getBody());
}
方法很简单,源码的复杂度也不高,可以看看。