How to access HTTP response headers after making an HTTP request with Apache HttpClient

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a very short recipe, Recipe 15.12, “How to access HTTP response headers after making an HTTP request with Apache HttpClient.”

Problem

You need to access the HTTP response headers after making an HTTP request in your Scala code.

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

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.