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;
}
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.
You can do it using commons-http-client library
Related
I am writing an blocking web client. I want to return both body(class) and http status code in ResponseEntity object to be used in some method. Can you please help with this. I am new to Java and already tried approaches many mentioned on internet.
You can use ResponseEntity class!
For e.g. Assume you want to return your Model/Pojo as below
Model class -> MyResponse (Has fields, getter/setters,toString etc) you want to respond along with HTTP code
Code snippet
#GetMapping("/getresponse) //Or any mapping
public ResponseEntity getResponse()
{
MyResponse response=new MyResponse();
return new ResponseEntity>(response,HttpStatus.OK);
}
How to Consume a Json Request,Coming from some other Application like ".Net" and i want to Consume that into my Java Application .
How to Consume this with Controller in Spring MVC .
Thanks
Shashank
If I'am able to understand your question then you are asking about how to Post JsonRequest to RestController, for that I'm attaching a code snippet and hope it helps.
Step1: Create a Model Class of that JSON Request.
Step2: Mark #RequestBody Annotation with Controller method to get that type of Object in Method argument.
#RequestMapping(value = "/getRequest", method = { RequestMethod.POST },
produces = {"application/json"})
public #ResponseBody Object getResponse(#RequestBody JsonRequest request) {
sysout("Json Body: "+request.toString());
}
you are basically asking how controllers work !! a controller's job is to handle any (JSON or ...) request to its services.
I suggest you read some articles about spring MVC and controllers to understand how it works.
https://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration
https://www.in28minutes.com/spring-mvc-tutorial-for-beginners
I'm working on a Spring MVC application and have a client that I have no control over. This client is POSTing JSON data but transmitting a application/x-www-form-urlencoded header. Spring naturally trusts this header and tries to receive the data but can't because its JSON. Has anyone had experience overriding the header that Spring receives or just specifying exactly what type of data is coming, regardless of the headers?
You can do two things;
Change the client to send the Content-Type:
application/json header
Write a Servlet Filter or Spring Interceptor which is on top of the Spring Controller and checks for the header Content-Type. If it is not application/json then it changes it to application/json.
Why don't you write a separate controller to handle application/x-www-form-urlencoded requests. If the request is a valid JSON, then you can parse it and forward it to to appropriate service.
This way you can also handle a case in future where you get request of same type which is not a valid JSON.
#RequestMapping(value = "/handleURLEncoded", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public #ResponseBody Object handleURLEncoded(HttpEntity<String> httpEntity) {
String json = httpEntity.getBody();
//now you have your request as a String
//you can manipulate it in any way
if(isJSONValid(json)) {
JSONObject jsonObj = new JSONObject(json);
//forward request or call service directly from here
//...
}
//other cases where it's not a valid JSON
}
Note: isJSONValid() method copied from this answer
I have a spring application which exchanges JSON with the mobile.
Spring controller looks like this:
#RequestMapping(value = "/register", method = RequestMethod.POST, headers = {"Content-type=application/json"})
public String register(#RequestBody #Valid UserRegistrationRequest urf, BindingResult bindingResult) {
return toJson(someResponse);
}
I wonder, what is the best way to log http request body and response body?
At the moment, I have custom json message converter and it logs a request body, before creating a bean out of json. and I use CustomTraceInterceptor to log a response body. Unfortunately, CustomTraceInterceptor doesn't allow to log request body.
Any advice for better solutions would be highly appreciated!
Thank you in advance.
Extend HandlerInterceptorAdapter, and override postHandle. Which has request and response injected into it.
You can also use new HttpServletResponseWrapper((HttpServletResponse) response) which has a more friendly api, and spring probably has even nicer wrapper as well ...
Can you point me to article or explain me how to declare RESTful web service which consumes JSON request and based on parameter inside JSON produces output in different formats, meaning customer can get output in JSON but in pdf also. I'm using Java and RestEasy on JBoss 5.1.
You could map the request on a method returning a RestEasy Response object, using a ResponseBuilder to build your response, setting dynamically the mime type of the response depending on a parameter in your JSON.
#POST
#Path("/foo")
#Consumes("application/json")
public Response fooService(MyObject obj) {
MyResponseEntity entity = MyObjectService.retrieveSomethingFrom(obj);
return Response.status(200).entity(entity).type(obj.isXml() ? "text/xml" : "application/json").build();
}
This way if your MyObject domain object that represent incoming JSON has a parameter xml set to true, then the Response object is parameterized to produce text/xml otherwise it produces application/json. RestEasy should do the rest.
You can use this way
#Path("/")
public class Test {
#Path("/test")
#POST
#Consumes("application/json")
#Produces("text/plain")
public Response addOrderJSON(OrderDetails details) {...}
}