Java Reference
In-Depth Information
}
@GET
@Produces("image/*")
public Response doGetAsImage() {
File image = new File(IMG_PATH);
if (!image.exists()) {
throw new WebApplicationException(404);
}
String type = new MimetypesFileTypeMap().getContentType(image);
return Response.ok(image, type).build();
}
@GET
@Produces("text/xml")
public String doGetAsXml() {
return "<?xml version='1.0' encoding='utf-8'?>" +
"<mascot>Xml Duke</mascot>";
}
}
This service is fairly straightforward except for a few things. One is that there are multiple
methods that claim to respond to HTTP GET requests, but they each respond with a different
MIME type, as indicated by their
@Produces
annotations. Note that in the
doGetAsImage
method, the value of the
@Produces
annotation indicates that it produces any image type. You
might instead specify
image/gif
as the produces type, but this allows that clients interested
in receiving an image type might match this with their
Accept
header more easily.
The class itself also contains an
@Produces
annotation, which means that the default MIME
will be
text/plain
. So despite the browser's declared preference for receiving HTML, this
class produces plain text unless you specifically indicate a single type you'll accept (you'll do
this later in your client). Therefore, if you open a regular browser and point to the class, you'll
see plain text, not HTML. All of the remaining GET methods are overrides for this default,
and will only be invoked in the event that there is a fairly specific match for the client's accept
type. For this reason, the
doGetAsPlainText
method needs no
@Produces
annotation.
The other thing that needs some clarification here is the way that you build the response in
the
doGetAsImage
method. It uses the
MimetypesFileTypeMap
class from the Java Activa-
tion framework to create a string representation of the actual MIME type of the file as read
from the server-side filesystem. In this case, the class examines the file you've passed to the
getContentType
method and determines its MIME, and then returns a string
image/gif
. So