Dynamically passing JSON/XML to REST web services - java

I have created a REST web services. Now the application which calls my web services says that will send a Header as RESPONSETYPE with value as JSON or XML. Based on this, I need to produce the response in json/xml. I understand that the Accept header can be used by sending the value as application/xml or application/json. But how can I achieve the dynamic response based on the custom header RESPONSETYPE?
Thanks in advance.

You should be able to do this by setting the MediaType explicitly in your Response object.
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getSomething(#HeaderParam("your-customer-header") String customHeaderType) {
return Response.ok(thingYouWantToReturn, mediaTypeFrom(customHeaderType)).build();
}
mediaTypeFrom is a method you'll need to determine what the actual MediaType to return is

Related

How a rest API will return both Json and XML response depending on the input header?

The code is as follow.Where I am checking the content type extracted from the header then I want to write the code and return the response from the same method.
#POST
#Produces(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_XML)
public Response addMessage(Message message , #Context UriInfo uriInfo,
#HeaderParam ("content-type") String contentType) throws
URISyntaxException
{
//Conditional check based on the content type.
if(contentType.equals("application/json")) {
return json;
}else {
return xml;
}
}
How a rest API will return both Json and XML response depending on the input header?
First , your usage of multiple #Produces on same method is incorrect. A String[] can be specified for all types that you wish to produce with #Produces , Annotation Type Produces
And for your main question, I agree with vlumi's comment that ,
You should just return the Response built with the object to return,
and let JAX-RS handle the serialization into XML or JSON, depending on
which the client expects/prefers
i.e. let the framework do it for you depending on Accept header as specified by client as Raj has already mentioned in comments,
You have to pass the request header Accept: application/json or
application/xml
Jersey Multiple Produces

Spring MVC Override Received Content Type

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

Content-type and #ResponseBody in spring

It could be very simple but it will be very helpful for me to understand...
I used #ResponseBody in my restcontroller to return String value to browser. The response string is successfully received in browser.
ie:
#RequestMapping(value="/foo", method=RequestMethod.GET)
#ResponseBody
public String foo() {
return "bar";
}
What is the content-type of above response? If this is going to be like writing setAttribute in servlet response what could the attribute name?
If the browser accept only "application/json" how spring will treat the response?
Submitted code produces text/html, as do all mapped Controller methods by default. If you want to produce application/json, you have to change your RequestMapping to
#RequestMapping(value="/foo", method=RequestMethod.GET, produces = "application/json")
However this is not a valid Json String, you would have to change it because the method you submitted would return empty body. The submitted example would be valid text/plain.
When the request contains header "Accept: application/json" and other content type is returned, Spring returns Json-type response explaining that HttpMediaTypeNotAcceptableException was thrown.
Regarding the servlet analogy - please explain, I don't fully understand what you mean. The String is returned as response body, it's very different from request attributes. What would you like to achieve?
I assume the content type will be plain/text. If the request sets accept to "application/json" it depends on your browser/tool. Most rest clients won't display it as it is not application/json. If you invoke the API directly I would assume it is displayed due to browser content sniffing (can be disabled via a header).

How to change the response content type for a Dropwizard REST service?

I took a look at the Dropwizard framework and I want to use it to package my existing REST service.
In the tutorial I noticed that the response content type is not set using a ResponseBuilder, can I set the reponse type like I would do for a regular REST service if it were not in a Dropwizard framework ?
The reason I want to set a dynamic response content type is because the webservice does not know the kind of data it is serving.
Thanks
You should be able to just return a Response object and adjust the type. For instance:
#Path("/hello")
#Produces(MediaType.TEXT_PLAIN)
public class Example{
#GET
public Response sayHello() {
return Response.ok("Hello world").type(MediaType.TEXT_HTML).build();
}
}

Consuming JSON request and producing different output

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) {...}
}

Categories

Resources