Reputation: 624
I am trying to understand the MIME types in RESTful services.If there is a resource method (sayHello) as in below
@Path("/customers")
public class CustomerResource {
@GET
public String sayHello(){
return "Hello World";
}
}
I didn't put any @Produces
or @Consumes
annotation on the above method. I have below questions.
Thanks in advance.
Upvotes: 2
Views: 1991
Reputation: 208974
Often it will default to application/octet-stream
, unless the client set the Accept
header, in which case, that's the type that will be used.
One thing you need to be careful about is that there is a not a MessageBodyWriter
to handle application/octet-stream
and most types. For instance say you have
@GET
public SomeModel get() {}
If the client doesn't set a Accept: application/json
header, then the runtime will look for a MessageBodyWriter
to that can serialize SomeModel
to application/octet-stream
, and it will fail and you will get an exception saying something like "No MessageBodyWriter found for mediatype application/octet-stream and type SomeModel".
So it is always a good idea to put the @Produces
. Another benefit is that you determine what types the endpoint can produce. For instance if you have @Produces("application/json")
, and the client set the Accept: application/xml
header, then they will get a 406 Not Acceptable error code, which is what should happen.
Notice the first paragraph, I used the word Often. It is not always the case. For some instances, the the runtime will make assumptions based on the return type. For instance if you return a String
it is likely the runtime will choose text/plain
.
But like I said, it's always better to have the @Produces
and @Consumes
annotations. These are hints not just for the developer but for the runtime to make decisions.
Upvotes: 1