web-servicesspringwebservice-clientresttemplatewebservicetemplate

How to Write RestTemplate for accessing Webservice (GET , POST)


I am unable to form the request parameter for consuming REST web service GET and POST, could any one please guide based on below scenario.

If I have REST webservice as below which is expecting two string parameters

General Web URL to consume webservice :

/myWs/sayHello?name=Peter&msg=Hai

//How to pass the arguments for getting GET and POST result.

 org.springframework.web.client.RestTemplate restTemplate = new RestTemplate();
 String url = "http://localhost:8080/myWs/sayHello";
 Map<String, String> vars = new HashMap<String, String>();
 vars.put("name", "peter");
 vars.put("msg", "Hai");
 String result = restTemplate.getForObject(url+"/{name}/{msg}", String.class, vars);
 String result1 = restTemplate.postForObject(url,  vars,String.class);

 System.out.println("GET result : "+result + "\nPOST result1"+result1);

Solution

  • This is how i normally perform a get:

    a. RestTemplate request

    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate();
    
    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    
    // Parameters
    StringBuilder params = new StringBuilder();
    params.append("?lat=");
    params.append(lat);
    params.append("&lng=");
    params.append(lng);
    
    // Make the HTTP GET request, marshaling the response from JSON to an array of Stations
    Object results = restTemplate.getForObject(URL + params.toString(), ServiceStationJsonModel.class); 
    
    // Do Something with the result
    

    b. Web Service

    @RequestMapping(value=URL, method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody Object nearmeServiceStationRequest(HttpServletRequest request) {
    
        String lat = request.getParameter("lat");
        String lng = request.getParameter("lng");
        // Do something with params
        ...
        return obj;
    }
    

    You can also use the @PathVariable annotations to get the parameters. An example of that as well of example on how to perform a post can be found here

    Hope this helps.