15.12. Setting URL Headers When Sending a Request

Problem

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

Solution

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

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.