Java @ Desk: Web Service | Java at your desk

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);
}


Add, get, set custom HttpHeader in request of HttpClient

Add, get, set custom HttpHeader in request of HttpClient

There are two ways to call the webservice using HTTP client one with Get method and other with Post method.

To add a header in HttpGet or HttpPost method, we need to use the addHeader() method which holds the key and value. Key in this has to be unique just like Map. You can add multiple headers.

How to call Rest CXF web service using HttpClient?

There are two ways to call the webservice using HTTP client one with Get method and other with Post method.

HttpClient call to GET webservice: Call a web service includes following steps:

1) Create the HttpGet object by passing the URL of the webservice
2) Append the request parameters if any in the URL

HttpGet get = new HttpGet("http://localhost:8080" + "/APP_NAME/JAXRS_ADDRESS/PATH" + "?" + "REQUEST_PARAM=REQUEST_VALUE");
3) Add the headers if any as shown below

get.addHeader("userId", );
get.addHeader("Service", );