- 获取restTemplate对象
- 封装请求头
- 封装请求参数
- 发起请求
- 获取返回值
获取restTemplate对象
1 RestTemplate restTemplate=new RestTemplate();
封装请求头
HttpHeaders requestHeaders = new HttpHeaders(); //添加session List<String> cookieLists =new ArrayList<String>(); String sessionStr="9338116b-a933-475b-aa4f-d785e9923125"; cookieLists.add("SESSION="+sessionStr); requestHeaders.put(HttpHeaders.COOKIE,cookieLists); //content-Type requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
封装请求参数
MultiValueMap<String, Object> reqParam=new LinkedMultiValueMap<>(); reqParam.add('key0','value0'); reqParam.add('key1','value1');
发起请求
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(reqParam,requestHeaders); String url="http://www.baidu.com"; ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Object.class);
获取返回值
Object obj= response.getBody();