Sumit Ghosh
Sumit Ghosh

Reputation: 514

Passing RequestParam data to Spring RestController

I am using restTemplate.exchangemethod to invoke one service from another service.My request url does accept a request parameter.

url is of the formhttp://localhost:8035/sgapp/student/fetchDeptNo?sid

In the conttroller it is written as

@RestController
@RequestMapping(value="/sgapp/student")
public class SiController{
     @GetMapping(value = "/fetchDeptNo",consumes = "application/x-www-form-urlencoded")
      public ResponseEntity<String> getSid(@RequestParam(name = "sid")String sid){
                  String sid = myRepo.getSidCode(sid);
                  System.out.println("sid received from DB::"+sid); 
                  return new ResponseEntity<String>(sid,HttpStatus.OK);
              }
        }

In the caller application I am invoking it as

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        Map paramMap = new HashMap<String, String>();
        paramMap.put("sid", sidData);
        HttpEntity<String> sidRespnse = restTemplate.exchange(
                "http://localhost:8035/sgapp/student/fetchDeptNo", HttpMethod.GET, entity, String.class,
                paramMap);

But I'm getting folllowing exception:

org.springframework.web.client.HttpClientErrorException: 400 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]

Can anyone provide any suitable solution to this???

Upvotes: 0

Views: 506

Answers (1)

Mike
Mike

Reputation: 5142

That particular exchange method is used to substitute variables into the path.

If you want to pass query parameters, use UriComponentsBuilder to create the URL with query params:

UriComponentsBuilder builder = 
    UriComponentsBuilder
        .fromHttpUrl(rootUri)
        .queryParam("sid", sidData);

Then you can use RestTemplate as follows:

restTemplate.exchange(
    builder.toUriString(),
    HttpMethod.GET,
    entity,
    String.class);

Upvotes: 2

Related Questions