Urbanleg
Urbanleg

Reputation: 6542

Spring MVC - creating an httprequest with java for a controller

here is one controller i got on my web application:

@RequestMapping(value = "/createAccount", method = RequestMethod.POST, consumes =     MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public ResponseDTO createAccount(@RequestBody PlayerAccountDTO playerAccountDTO,
        HttpServletRequest request) {

    this.playerService.createAccount(playerAccountDTO);

    return new ResponseDTO();
}

This controller is being called via ajax using post and passing a json and jackson mapper takes care for it to arrive as a POJO (Nice!)

What i would like to do now is: In a different web application i would like to call with http post request passing PlayerAccountDTO to this exact controller and ofcourse recieve the ResponseDTO.

I would like that to be as simple as possible.

Is it possible to achieve that? here is my wishfull solution (a service on a different web app):

public ResponseDTO createAccountOnADifferentWebApp() {

    PlayerAccountDTO dto = new PlayerAccountDTO(...);

    ResponseDTO result = httpRequestPost(url, dto, ResponseDTO.class);

            return result;
}

Upvotes: 0

Views: 1367

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280171

Your web server doesn't receive a PlayerAccountDTO object. It receives an HTTP request with a body that (likely) contains a JSON object. The Spring web application tries to deserialize that JSON into a PlayerAccountDTO object which it passes to your handler method.

So what you want to do is use an HTTP client which serializes your PlayerAcocuntDTO on the client side into some JSON which you send in an HTTP request.

Check out RestTemplate which is a Spring HTTP client and uses the same HttpMessageConverter objects that Spring uses to serialize and deserialize objects in @ResponseBody annotated methods and @RequestBody annotated parameters.

Upvotes: 1

sanbhat
sanbhat

Reputation: 17622

You can do it using commons-http-client library

Upvotes: 0

Related Questions