Search code examples
javaspring-mvcresttemplate

RestTemplate for @RequestBody and @RequestParam


I'm trying to use RestTemplate to call POST api like that :

RequestorParam  test = new RequestorParam();
test.setScopeMcg("MCG");
test.setSituatedDealIds(situatedDealIds);

String url = "http://localhost:" + serverPort + "/retrieveAttributes";
ResponseEntity<SituatedDeals> response = restTemplate.postForEntity(url, test, SituatedDeals.class);

and the code of the controller is like ;

  @PostMapping(value = "/retrieveAttributes", produces = "application/json")
  @ResponseBody
  @Duration
  public SituatedDeals retrieveAttributes(
        @RequestParam String scopeMcg, 
        @RequestBody SituatedDealIds situatedDealIds 
    ) {
        log.info("success")
  }

i'm getting bad request, can someone help ?


Solution

    1. According to your controller code, you are actually not returning any Response Entity of type SituatedDeals, just logging it as success. this might be the reason for the null object in response.

    2. The scopeMcg is a RequestParameter so you should be passing it in a request param format i.e http://localhost:8080/retrieveAttributes?scopeMcg=MCG Reference:Spring Request Param

    3. Your test Object is the actual payload for your post request which should be of type SituatedDealIds object. Reference: Rest-Template post for Entity