Question

I have a server and a client. I am using Spring to map http requests on the server and RestTemplate to make requests to the server.

Server code looks like this:

@RequestMapping (value="/someEndPoint", method = RequestMethod.POST)
@ResponseBody
public String configureSettings(
@RequestParam(required=false) Integer param1,
@RequestParam(required=false) Long param2,
@RequestBody String body)
{

if(param1 != null)
// do something

if(body not empty or null)
//do something

} 

Client side:

String postUrl = "http://myhost:8080/someEndPoint?param1=val1"
restTemplate.postForLocation(postUrl, null);

This works in that the correct action is triggered on the server side from param1 however, the body of the request also contains:
param1=val1
The request body when it is set it will json so all I want is to be able to set other parameters without setting the body. I know I am using the restTemplate incorrectly so any help would be greatly appreciated.

Was it helpful?

Solution

You are doing an HTTP POST, but you are not providing an object to put POSTed. Spring's RestTemplate is trying to figure out what you want to POST, so it looks and sees that the query string of the url has something, so it tries to use that.

Do not add a query string to a POST, just provide the object that you want to POST.

String postUrl = "http://myhost:8080/someEndPoint"
restTemplate.postForLocation(postUrl, new ParamModel("val1"));

The book Spring in Action (3rd edition) covers RestTemplate (and REST in general) pretty well. I would recommend taking a look at it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top