how i can pass parameters in restTemplate to controller's put method

Viewed 208

I have a problem with passing parameters. I have names in my income app and i want to update them by passing a parameters of new names from my rest app. This is my code:

String url = "http://localhost:8084/rest/api/income/UpdateName/{oldName}/{newName}"; // the Url of the rest


    Map<String, String> params = new HashMap<>();
    params.put("oldName", oldName);
    params.put("newName", newName);
    Income income = new Income();

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.put(url, income, params);
    System.out.println(params);
}    

This code is not working unfortunately, what can I do?

This is the put method in the controller :

@CrossOrigin
@GetMapping("/UpdateName/{oldName}/{clientName}") // view all incomes ..
public GeneralResponse viewAllIncome(@PathVariable("oldName") String oldName,@PathVariable("clientName") String clientName) {

    return new GeneralResponse(incomeServiceTemplate.updateClientName(oldName,clientName));

}    
1 Answers

The endpoint is GET not PUT, just append the parameters in the URL and call:

String url = "http://localhost:8084/rest/api/income/UpdateName/"+oldName+"/"+newName;

RestTemplate restTemplate = new RestTemplate();
restTemplate.getForObject(url, Income.class);

Or there's a better way, use uriComponentsBuilder. It takes care of url encoding:

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
    .queryParam("oldName", oldName)
    .queryParam("newName", newName);
restTemplate.getForEntity(builder.build().encode().toUri(), Income.class);
Related