Class AcceptHeader


  • public final class AcceptHeader
    extends Object
    Represents the Accept HTTP header and help server choose the right media type to serve.

    Typical usage:

     HttpResponse doXyz(@Header("Accept") AcceptHeader accept, ...) {
         switch (accept.select("application/json","text/xml")) {
         case "application/json":
             ...
         case "text/html":
             ...
         }
     }
     

    A port to Java of Joe Gregorio's MIME-Type Parser: http://code.google.com/p/mimeparse/ Ported by Tom Zellman <tzellman@gmail.com>.

    See Also:
    definition of Accept header
    • Constructor Detail

      • AcceptHeader

        public AcceptHeader​(String ranges)
        Parse the accept header value into a typed object.
        Parameters:
        ranges - something like "text/*;q=0.5,*; q=0.1"
    • Method Detail

      • match

        @Nullable
        protected AcceptHeader.Atom match​(String mimeType)
        Given a MIME type, find the entry from this Accept header that fits the best.
      • select

        public String select​(Iterable<String> supported)
        Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types.
        
         // Client: I prefer text/*, but if not I'm happy to take anything
         // Server: I can serve you xbel or xml
         // Result: let's serve you text/xml
         new AcceptHeader("text/*;q=0.5, *;q=0.1").select("application/xbel+xml", "text/xml") => "text/xml"
        
         // Client: I want image, ideally PNG
         // Server: I can give you plain text or XML
         // Result: there's nothing to serve you here
         new AcceptHeader("image/*;q=0.5, image/png;q=1").select("text/plain","text/xml") => null
         
        Returns:
        null if none of the choices in supported is acceptable to the client.