spring rest client, how to serialize object in client request

2k Views Asked by At

On client I have

RestTemplate restTemplate = new RestTemplate();
Result r = restTemplate.getForObject("http://localhost:8080/test?key1=value1",Result.class);

I don't want to manually append "key1=value1" to the url, is it possible to have a class like

class Dto {
  private String key1;
  public void setKey1(String key1) {this.key1=key1}

and have spring to automatically serialize the dto object, so the call would be like

Result r = restTemplate.getForObject("http://localhost:8080/test", Result.class, dto);

There is such method in restTemplate, but I can't get it to work, on server side I receive empty object. I guess I am missing some annotations on the DTO. On server I have

@RequestMapping(value = "/test")
@ResponseBody
public DTO test(DTO p) {
    p.setName("received");
    return p;
}

Please advice.

1

There are 1 best solutions below

1
On

considering that you are keeping all endpoints as a constant in a file, you should use place holders in url. In your case one URL endpoint would be http://localhost:8080/test?key1={0}&anotherParam={1} and while you do

restTemplate.getForObject("http://localhost:8080/test", Result.class, "keyVal","anotherKeyVal");

since last parameter is of type varArgs it will take as many values as you want to send but in the same order in which you have define the keys in the seed URL. putting them at there place holders is taken care of by the API itself. [Updated] looking at your server side code it seems you want to receive your values inside DTO object. for this you need to POST(and make the endpoint as POST) the data using messageConverter(JSON or XML). that way your object will be marshalled and unmarshalled by your messageConverter.