HTTP header parsing

If you already established a URLConnection (HttpURLConnection or HttpsURLConnection) you can get the content or headers and parse them yourself.

But why not use the method getHeaderFields provided by URLConnection?  All you need is to understand Java Collections because it returns a Map. Have a look at the Trail: Collections (by Josh Bloch).

You might test argue why not use getDate provided by URLConnection. Good point! I have not looked into that issue enough to tell you for sure it returns the desired long in any case. So for now, in my idiosyncrasy, I try to handle the header Date field on my own.

Enjoy the code using generics:

Map<String,List<String>> map = urlConnection.getHeaderFields();
Set<Entry<String,List<String>>> set = map.entrySet();
Iterator<Entry<String,List<String>>> iterator = set.iterator();
boolean cookie;
boolean headerDate;
while (iterator.hasNext())
{
  Entry<String,List<String>> entry = iterator.next();
  String key = entry.getKey();
  if(key!=null)
  {
    cookie = key.equals("Set-Cookie");
    headerDate = key.equals("Date");
    if(cookie || headerDate)
    {
      List<String> list = entry.getValue();
      Iterator<String> listIterator = list.iterator();
      while (listIterator.hasNext())
      {
        String listElement = listIterator.next();
        if(headerDate)
        {
        ...
        }
        else if(cookie)
        {
        ...
        }
      }
    }
  }
}

Using for loops

Things have been improved a bit. No iterator needed anymore.

String url = "https://example.com";
Map<String,List<String>> headerFields;
try {
  URLConnection connection = new URL(url).openConnection();
  headerFields = connection.getHeaderFields();
  Set<String> keyStrings = headerFields.keySet();
  for (String key : keyStrings) {
    System.out.print(key + ": ");
    for (String value : headerFields.get(key)) {
      System.out.print(value + " ");
    }
    System.out.print("\n");
  }
}
catch (IOException ioe) {
  System.err.println(ioe);
}

Java 8


Now let us look at how you can do it today. Yeah! We may use Lambda funtions. First you get a Stream of the Lists of Strings. Next step is to use the Collectors to create the actual String from the List joined by spaces.

headerFields = connection.getHeaderFields();
headerFields.forEach((k, v) -> {
  if(k != null && k.equals("Set-Cookie")) {
  System.out.println(k + ": " + v.stream()
    .collect(Collectors.joining(" ")));
  }
});

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.