scalahttp-status-code-301http-redirectscala-dispatch

How do I use Scala dispatch to get the URL returned in a 301 redirect?


I am using Scala dispatch HTTP library, version 0.10.1. I make a request to a URL that returns an HTTP 301, permanent redirect. For example, http://wikipedia.com returns a 301 that redirects to http://www.wikipedia.org/. How do I do I use dispatch to get the redirected URL?

Following the tutorial, here's what I've done.

import dispatch._, Defaults._
val svc = url("http://wikipedia.com")
val r = Http(svc OK as.String)
r()

This throws a "Unexpected response status: 301" exception. Presumably I need to either query the r value for the redirected URL, or maybe specify some argument other than OK in its definition, but I can't figure out what to do from the documentation.


Solution

  • Configure the underlying asyncClient to follow redirects:

    val r = Http.configure(_ setFollowRedirects true)(svc OK as.String)
    

    To get the redirected URL:

    val svc = url("http://wikipedia.com/")
    val r = Http(svc > (x => x))
    val res = r()
    
    println(res.getHeader("Location"))