Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 281
W.P. McNeill Avatar asked Jun 14 '13 15:06

W.P. McNeill


1 Answers

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"))
like image 197
gnf Avatar answered Oct 15 '22 22:10

gnf