Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

getHeader and getHeaders methods

Jan van Mansum
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello group:

Here's a point that confused me a bit, but I think I understand now. HttpServletRequest.getHeader(String n) returns the first header of name "n" and HttpServletRequest.getHeaders(String n) returns all the headers of name "n" as an Enumeration.

What confused me was that I thought "multiple values" meant something like:

accept: text/html, image/gif

value1 = text/html
value2 = image/gif

But when I tried this out I got the whole string "text/html, image/gif" when calling getHeader("accept"). OK, so I figure that "multiple values" would then be:

accept: text/html
accept: image/gif

Now, my question is: when does the browser send its request in this form?
Marc Peabody
pie sneak
Posts: 4727
Mac Ruby VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

From getHeader of HttpServletRequest 1.4 API:
Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. If there are multiple headers with the same name, this method returns the first head in the request. The header name is case insensitive. You can use this method with any request header.

However the HTTP 1.1 RFC says this (and the 1.0 is similar):
Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma. The order in which header fields with the same field-name are received is therefore significant to the interpretation of the combined field value, and thus a proxy MUST NOT change the order of these field values when a message is forwarded.

My guess is that once upon a time there was some browser or other application that didn't play by HTTP rules and Java had to provide a way around it. From the looks of it, there's no good reason why anyone should ever use getHeaders... unless they miraculously find the app that submits HTTP headers that don't follow the rules.
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!