How to set HTTP headers when sending a web service request

Summary: This post is an excerpt from the Scala Cookbook, partially modified for the internet. This is a short recipe, Recipe 15.13, “How to set HTTP headers when sending a web service request.”

Problem

You need to set URL headers when making an HTTP request in Scala.

Solution

The easiest way to set HTTP headers when calling a web service is to use the Apache HttpClient library to set the headers before making the request, as shown in this example:

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

object SetUrlHeaders extends App {
    val url = "http://localhost:9001/baz"
    val httpGet = new HttpGet(url)

    // set the desired header values
    httpGet.setHeader("KEY1", "VALUE1")
    httpGet.setHeader("KEY2", "VALUE2")

    // execute the request
    val client = new DefaultHttpClient
    client.execute(httpGet)
    client.getConnectionManager.shutdown
}

Discussion

If you don’t have a web server to test against, you can use a tool like HttpTea to see the results of running this program. HttpTea helps to simulate a server in a test environment. Start HttpTea at the command line to listen on port 9001 like this:

$ java -jar HttpTea.jar -l 9001

Now when you run your client program — such as the program shown in the Solution — you should see the following output from HttpTea, including the headers that were set:

Client>>>
GET /baz HTTP/1.1
KEY1: VALUE1
KEY2: VALUE2
Host: localhost:9001
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.3 (java 1.5)

See Also