3: Making Other Types of Requests

Making HEAD Requests

The GET requests are the most familiar of those available to us, but not the simplest. HEAD requests are simpler but rarely used; they’re not useful for much other than testing URL status. Let’s see an example that is similar to those we saw earlier.

import uk.co.bigbeeconsultants.http._

object Example3a {
  val httpClient = new HttpClient

  def main(args: Array[String]) {
    val response = httpClient.head("http://www.google.com/")

    println(response.body.contentLength) // prints 0
    println(response.body.asString.length) // the same number
    println(response.body.contentType.madiaType) // prints "text/html"
    println(response.body.contentType.charsetOrUTF8) // prints "ISO-8859-1"
  }
}

With a HEAD request, the response won’t contain any content, although it will normally contain the same headers that were received by the equivalent GET (unless a particular server doesn’t behave that way).

Making POST Requests

A POST request can have a request body - the data that is being posted. This is done easily using a string to supply the data, or you can use a Map[String, String] if handling form parameters, or you can supply an InputStream if the data is streamed in. This example uses a map body, behaving like a form submission.

import uk.co.bigbeeconsultants.http._
import uk.co.bigbeeconsultants.http.request.RequestBody

object Example3b {
  val requestBody = RequestBody(Map("x" -> "1", "y" -> "2"))
  val url = "http://beeclient/test-echo-back.php"
  val httpClient = new HttpClient

  def main(args: Array[String]) {
    val response = httpClient.post(url, Some(requestBody))
    println(response.status)
    println(response.body)
  }
}

If you run this example, we called a PHP script that is included in the test resources with the Light HTTP Client source code - it merely echoes back the data it received in a plain-text listing.

In normal practice, however, when following a POST method, a well-behaving server will issue a 303-See other status, along with the corresponding location header.

Making PUT Requests

A PUT request must have a request body - the data that is being put. This example uses a string body instead of a map.

import uk.co.bigbeeconsultants.http._
import uk.co.bigbeeconsultants.http.request.RequestBody
import uk.co.bigbeeconsultants.http.header.MediaType._

object Example3c {
  val jsonBody = RequestBody( """{ "x": 1, "y": true }""", APPLICATION_JSON)
  val url = "http://beeclient/test-echo-back.php"
  val httpClient = new HttpClient

  def main(args: Array[String]) {
    val response = httpClient.put(url, jsonBody)
    println(response.status)
    println(response.body)
  }
}

Other Requests

In addition to HEAD, GET, POST and PUT, Bee Client also supports DELETE, OPTIONS and TRACE. These are similar in use to the examples given above.