Spring Rest Template Pass parameters in URL - Java @ Desk

Saturday, September 2, 2017

Spring Rest Template Pass parameters in URL

Spring Rest Template Pass parameters in URL

Spring RestTemplate - org.springframework.web.client.RestTemplate helps in accessing the third party Rest Services. The methods used to get or post the data is similar to what we have learned in the past.

Following are the important methods to get/post/put/delete the data headForHeaders(), getForObject(), postForObject(), put() and delete() etc.

Below example is the rest service that passes the data in the URL and the same is retrieved using the @PathVariable - import org.springframework.web.bind.annotation.PathVariable; annotation as a method argument in rest service.
Below method is the RequestMapping that expects the Path Variable id from the caller.

@RequestMapping(value = "/person/{id}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createEmployee(@PathVariable("id") int id) {
 System.out.println("Path Variable Id - " + id);
 return new ResponseEntity<String>("success", HttpStatus.OK);
}


Client Code to call the rest service -
private static void createEmployee() {
 final String uri = "http://localhost:8080/resttemplate/person/10";

 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "1");
 RestTemplate restTemplate = new RestTemplate();
 String result = restTemplate.getForObject(uri, String.class, params);

 System.out.println(result);
}








No comments:

Post a Comment