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

By Alvin Alexander. Last updated: December 7, 2021

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: 2012年7月15日 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: 1978年11月19日 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

alvinalexander.com
is owned and operated by
Valley Programming, LLC

In regards to links to Amazon.com, As an Amazon Associate
I (Valley Programming, LLC) earn from qualifying purchases

This website uses cookies: learn more

AltStyle によって変換されたページ (->オリジナル) /