Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass custom objects using Spring's REST Template

I have a requirement to pass a custom object using RESTTemplate to my REST service.

RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
...

requestMap.add("file1", new FileSystemResource(..);
requestMap.add("Content-Type","text/html");
requestMap.add("accept", "text/html");
requestMap.add("myobject",new CustomObject()); // This is not working
System.out.println("Before Posting Request........");
restTemplate.postForLocation(url, requestMap);//Posting the data.
System.out.println("Request has been executed........");

I'm not able to add my custom object to MultiValueMap. Request generation is getting failed.

Can someone helps me to find a way for this? I can simply pass a string object without problem.User defined objects makes the problem.

Appreciate any help !!!

like image 935
ASChakkalakal Avatar asked Jun 13 '12 11:06

ASChakkalakal


People also ask

How do you use postForEntity RestTemplate?

Using postForEntity()Find the postForEntity method declaration from Spring doc. url: The URL to post the request. request: The object to be posted. responseType: The type of response body.

How do you parse a RestTemplate response?

You can use the annotation @JsonRootName to specify the root element in your response. So try this: @JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName(value ="result") public class User { public User(){ } private boolean admin; .... }


1 Answers

You can do it fairly simply with Jackson.

Here is what I wrote for a Post of a simple POJO.

@XmlRootElement(name="newobject")
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class NewObject{
    private String stuff;

    public String getStuff(){
        return this.stuff;
    }

    public void setStuff(String stuff){
        this.stuff = stuff;
    }
}

....
//make the object
NewObject obj = new NewObject();
obj.setStuff("stuff");

//set your headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

//set your entity to send
HttpEntity entity = new HttpEntity(obj,headers);

// send it!
ResponseEntity<String> out = restTemplate.exchange("url", HttpMethod.POST, entity
    , String.class);

The link above should tell you how to set it up if needed. Its a pretty good tutorial.

like image 63
Chris Avatar answered Sep 28 '22 10:09

Chris