scalahttpheaderrequestscala-dispatch

How to get response headers and body in dispatch request?


I want to get both body and headers from dispatch request. How to do this?

val response = Http(request OK as.String)
for (r <- response) yield {
  println(r.toString) //prints body
  // println(r.getHeaders) // ???? how to print headers here ???? 
}

Solution

  • From the Dispatch docs:

    import dispatch._, Defaults._
    val svc = url("http://api.hostip.info/country.php")
    val country = Http(svc OK as.String)
    

    The above defines and initiates a request to the given host where 2xx responses are handled as a string. Since Dispatch is fully asynchronous, country represents a future of the string rather than the string itself. (source)

    In your example, the type of response is Future[String], because 'OK as.String' converts 2xx responses into strings and non-2xx responses into failed futures. If you remove 'OK as.String', you'll get a Future[com.ning.http.client.Response]. You can then use getResponseBody, getHeaders, etc. to inspect the Request object.