There are two ways for sending parameters in an Http Get
method. PathVariable
and RequestParam
. In this way, sent parameters are visible in the request URL. for example:
www.sampleAddress.com/countries/{parameter1}/get-time?city=someValues
In the above request, parameter1
is a path variable and parameter2
is a request parameter. So an example of a valid URL would be:
www.sampleAddress.com/countries/Germany/get-time?city=berlin
To access these parameters in a java controller, you need to define a specific name for the parameters. For example the following controller will receive this type of requests:
@GetMapping(value = "/countries/{parameter1}/get-time", produces = "application/json; charset=utf-8")
public String getTimeOfCities(
@PathVariable(value = "parameter1") String country,
@RequestParam(value = "city") String city
){
return "the method is not implemented yet";
}
You are able to send RequestBody
through a Get
request but it is not recommended according to this link.
yes, you can send a body with GET, and no, it is never useful
to do so.
This elaboration in elasticsearch website is nice too:
The HTTP libraries of certain languages (notably JavaScript) don’t allow GET requests to have a request body. In fact, some users are suprised that GET requests are ever allowed to have a body.
The truth is that RFC 7231—the RFC that deals with HTTP semantics and
content—does not define what should happen to a GET request with a
body! As a result, some HTTP servers allow it, and some—especially
caching proxies—don’t.
If you want to use Post
method, you are able to have RequestBody
too. In the case you want to send data by a post request, an appropriate controller would be like this:
@PostMapping(value = "/countries/{parameter1}/get-time", produces = "application/json; charset=utf-8")
public String getTimeOfCitiesByPost(
@PathVariable(value = "parameter1") String country,
@RequestParam(value = "city") String city,
@RequestBody Object myCustomObject
){
return "the method is not implemented yet";
}
myCustomObject
could have any type of data you defined in your code. Note that in this way, you should send request body as a Json
string.