Java Reference
In-Depth Information
Viewing Accept headers
In Chapter 5 , you were introduced to javax.ws.rs.core.HttpHeaders , the JAX-RS utility
interface. This interface contains some preprocessed conneg information about the incoming
HTTP request:
public
public interface
interface HttpHeaders
HttpHeaders {
public
public List < MediaType > getAcceptableMediaTypes ();
public
public List < Locale > getAcceptableLanguages ();
...
}
The getAcceptableMediaTypes() method contains a list of media types defined in the
HTTP request's Accept header. It is preparsed and represented as a
javax.ws.rs.core.MediaType . The returned list is also sorted based on the “q” values (ex-
plicit or implicit) of the preferred media types, with the most desired listed first.
The getAcceptableLanguages() method processes the HTTP request's Accept-Language
header. It is preparsed and represented as a list of java.util.Locale objects. As with
getAcceptableMediaTypes() , the returned list is sorted based on the “q” values of the pre-
ferred languages, with the most desired listed first.
You inject a reference to HttpHeaders using the @javax.ws.rs.core.Context annotation.
Here's how your code might look:
@Path ( "/myservice" )
public
public class
class MyService
MyService {
@GET
public
public Response get ( @Context HttpHeaders headers ) {
MediaType type = headers . getAcceptableMediaTypes (). get ( 0 );
Locale language = headers . getAcceptableLanguages (). get ( 0 );
Object responseObject = ...;
Response . ResponseBuilder builder = Response . ok ( responseObject , type );
builder . language ( language );
return
return builder . build ();
}
}
Search WWH ::




Custom Search