15.11. Getting URL Headers

Problem

You need to access the HTTP response headers after making an HTTP request.

Solution

Use the Apache HttpClient library, and get the headers from the HttpResponse object after making a request:

import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.DefaultHttpClient

object FetchUrlHeaders extends App {

  val get = new HttpGet("http://alvinalexander.com/")
  val client = new DefaultHttpClient
  val response = client.execute(get)
  response.getAllHeaders.foreach(header => println(header))

}

Running that program prints the following header output:

Server: nginx/1.0.10
Date: Sun, 15 Jul 2012 19:10:19 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Keep-Alive: timeout=20
Content-Length: 28862
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Vary: Accept-Encoding

Discussion

When I worked with a Single Sign-On (SSO) system named OpenSSO from Sun (now known as OpenAM), much of the work in the sign-on process involved setting and reading header information. The HttpClient library greatly simplifies this process.

See Also

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.