Search code examples
scalascala-dispatch

how to get the response content with dispatch?


I have looked at the dispatch tutorial, and can easily find how to get the header information (if the status is 200, if I have understood other posts) for instance with;

def main(args: Array[String]){ 
    val svc = url("http://www.google.com")
    val country = Http(svc OK as.String)
    for (c <- country){
        println(c)
    }
}

However, I can not find how to get the response content. I would be thankful if someone could help me with that. I assume it should be a function applied on svc.


Solution

  • The documentation explains it:

    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.

    (emphasis mine) where country refers to the request from your example and your example actually returns the body.

    Note that your code example explicitely casts into String, but you can get the raw response object like this:

    val svc = url("http://www.google.com")
    val request = Http(svc)
    val response = request()
    print(s"Status\n  ${response.getStatusCode}\nHeaders:\n  ${response.getHeaders}\nBody:\n  ${response.getResponseBody}")
    

    This gets you the HTTP status code, all response headers and the entire response body.

    See the entire reference for the Response here