rgh rgh - 1 month ago 6
HTTP Question

What is the point of URLConnection.getHeaderFields() returning a Map<String,List<String>>

I can't see the value in this method returning a Map<String List<String>> instead of simply Map<String, String>

I was expecting Map<String List<String>> to be of value when a web server returns more than one value in a given header. It's legal for several values to be returned as a comma delimited list. I've seen this most often with Cache-Control. I'd expect each value to be an item in the list. However, that's not the case:

import java.net.*;
import java.io.*;
import java.util.*;

class URLConnectionDemo {
private static final String DEFAULT_URL = "http://stackoverflow.com";
public static void main(String[] args) {
URL url;
URLConnection urlConnection;
try {
url = new URL((args.length==0) ? DEFAULT_URL : args[0]);
urlConnection = url.openConnection();
Map<String, List<String>> headerMap = urlConnection.getHeaderFields();
System.out.printf("Header count = %d\n", headerMap.size());
for(String key:headerMap.keySet()){
System.out.printf("%s:\n", key);
List<String> valuesList = headerMap.get(key);
for(String value:valuesList){
System.out.printf(" %s\n", value);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}


Output:

Header count = 19
null:
HTTP/1.1 200 OK
....many other headers....
Cache-Control:
public, max-age=7


The Cache-Control values are just returned as a single String.

So, are there any circumstances where the header value List<String> is of any use?

Solution:

I'm using a servlet on Tomcat to try & generate duplicated http response headers.

In the servlet code, using repeated calls to
HttpServletResponse.addHeader()
with duplicated header names doesn't work. All the header values get consolidated into a single comma separated value.

However, that's not allowed for adding cookies. If I use
HttpServletResponse.addCookie()
several times, I get several distinct Set-Cookie headers. These do indeed end up as distinct Strings in the List.

Answer
field_name: field_value1, field_value2, field_value3

in HTTP Header gives 1 string in the list of corresponding map entry, while semantically equivalent

field_name: field_value1
field_name: field_value2
field_name: field_value3

will give 3 strings.

However not all values with the same field name may be combined into field values list. For example, in RFC 7230 we may read

Note: In practice, the "Set-Cookie" header field ([RFC6265]) often appears multiple times in a response message and does not use the list syntax, violating the above requirements on multiple header fields with the same name. Since it cannot be combined into a single field-value, recipients ought to handle "Set-Cookie" as a special case while processing header fields. (See Appendix A.2.3 of [Kri2001] for details.)