Search code examples
jsonspring-mvccurlspring-roo

Issue with a CURL GET request and Spring Mvc request mappings


I am trying to GET the following method using CURL:

@RooWebJson(jsonObject = Geolocation.class)
@Controller
@RequestMapping("/geolocations")
public class GeolocationController {

    @Autowired
    private GeolocationRepository geolocationRepository;

    @RequestMapping(params = "findByPostcodeFirstChars", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> jsonFindGeolocationsByPostcodeFirstChars(@RequestParam("postcodeFirstChars") String postcodeFirstChars) {
        System.out.println("jsonFindGeolocationsByPostcodeFirstChars");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        List<Geolocation> geolocations = geolocationRepository.findByPostcodeStartingWith(postcodeFirstChars);
        return new ResponseEntity<String>(Geolocation.toJsonArray(geolocations), headers, HttpStatus.OK);
    }
}

I use CURL as follows:

 curl -i -H Accept:application/json http://localhost:8080/kadjoukor/geolocations?findByPostcodeFirstChars%26postcodeFirstChars=7500

However, the above CURL command always GET this method (from the Roo ITD) instead of the above one:

@RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> GeolocationController.listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        List<Geolocation> result = geolocationRepository.findAll();
        return new ResponseEntity<String>(Geolocation.toJsonArray(result), headers, HttpStatus.OK);
    }

I am not sure what I get wrong. Can someone please help?


Solution

  • I was getting the CURL syntax wrong.

    I shouldn't have tried to encode the ampersand manually. This was the cause of the problem.

    Here is the appropriate way of sending the GET request:

    curl -i -X GET -H Accept:application/json "http://localhost:8080/kadjoukor/geolocations?findByPostcodeFirstChars&postcodeFirstChars=7500"
    

    Notice the quotes and the &