1/08/2013

Spring rest template API call

If "POST"

01 HttpEntity<Login> entity = new HttpEntity<Login>(
02                 domain, createHeaders(MediaType.APPLICATION_JSON));
03 LOGGER.debug("--> " + entity.getHeaders());
04         
05 ResponseEntity<DomainsClientBean> response = restTemplate.exchange(
06                     url, HttpMethod.POST, entity, Login.class);
07 
08 
09 private HttpHeaders createHeaders(MediaType mediaType{
10         HttpHeaders res = new HttpHeaders();
11         List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(2);
12         acceptableMediaTypes.add(mediaType);
13         res.setAccept(acceptableMediaTypes);
14         res.setContentType(mediaType);
15         res.add("customized header1", "header1");
16         res.add("customized header2", "header2");
17         
18         return res;
19 }

If "GET"

01 String url = API_URL + "?userName=" + userName;
02 
03 HttpEntity<?> entity = new HttpEntity<Object>(createHeaders(MediaType.APPLICATION_JSON));
04         
05 LOGGER.debug("--> " + entity.getHeaders());
06   
07 ResponseEntity<StatusResponse> response = restTemplate.exchange(
08                     url, HttpMethod.GET, entity, StatusResponse.class);        
09   
10 if (response.getBody() == null{
11 
12   return false;
13 }        
14   
15 return response.getBody(); //response body is Status Response object

If using "GET", it needs to be careful that HttpEntity<?> entity = new HttpEntity<Object>(...);
This line should in this format, HttpEntity is <?> Type and HttpEntity is<Object> type.
Or, personal experience, the API call may lose the parameters that passed in url. 

No comments:

Post a Comment